js一些技巧
# js一些技巧
# 1. 事件只响应一次
element.addEventListener("click",()=>{console.log("I run only once"),{
once:true
}})
# 2.复制到剪贴板
使用 clipboard
function copy(text){
navigator.clipboard.writeText(text)
}
# 3. 实用判断语句
如果想判断条件为true时执行函数,则可以使用 &&简写
if(condition){doSomething()} //原始写法
condition && doSomething() //现有写法
为虚值给空值 非常常用
const data = result.data.arry|| [] //如果为空,将空数组赋值给data
如果不进行判断,一旦返回为空,data为undeined ,在后续执行一些方法时就会报错阻塞代码执行
# 4. 交换变量的值
let a=1,b=2;
[a,b]=[b,a]
console.log(a,b) //2,1
# 5.获取变量的类型
const ifTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
# 6.在指定位置截取之前或者之后的字符串
const str = 'hellow_world'
str.substring(str.indexOf('_')+1) //word
str.substring(str.indexOf('_'), -1) //hello
编辑 (opens new window)
上次更新: 2022/05/28, 10:34:23