1. // 与 ??
// 左侧为空、false、null、undefined等falsy值时返回后面的值
let arr = ['',0,-0,+0,NaN,false,undefined,null]
arr.forEach(item => console.log(item||'some other'))
some other
some other
some other
some other
some other
some other
some other
some other
?? 左侧为null或undefined时返回后面的值,否则返回前面的值
let arr = ['',0,-0,+0,NaN,false,undefined,null]
arr.forEach(item => console.log(item??'some other'))
0
-0
0
NaN
false
some other
some other
2. 数组合并
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = a.concat(b)
for(let i in b) {
a.push(b[i])
}
a.push.apply(a,b) // apply第二个参数可为数组
let d = [...a,...b]
3. forEach提前退出
使用break会报错,使用return也不能跳出循环。
用 try···catch 捕获异常实现
try {
let arr = [1,2,3,4,5]
arr.forEach((item,index) => {
if(item == 3) {
// 一 代码错误跳出
let err = xxx;
// 二 抛出异常跳出
// throw new Error('break');
} else {
console.log(item);
}
})
} catch (error) {
if(error.message=='break') {
console.log('提前结束循环啦');
} else{
console.log(error.message);
}
}