这是该系列的第29篇笔记!
让学习“上瘾”,成为更好的自己!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>数组的空位</title>
</head>
<body>
<script>
// 数组的空位: 指数组的某个位置没有任何值,比如,Array构造函数的数组都是空位
// console.log(Array(3));
// 【注意】空位不是undefined,一个位置的值等于undefined依然有值的
// 空位是没有任何值的,in运算符可以说明这一点
// console.log(0 in [undefined, undefined, undefined]); // true --> 该数组的0号位置是有值的
// console.log(0 in [, , ]); // false --> 该数组的0号位置是没有值的
// ES5对空位的处理很不一致
// forEach方法
[, 'a'].forEach((x, i) => console.log(i)); // 1
// filter
console.log(['b', , 'a'].filter(x => true)); // ["b", "a"]
// every
console.log([ , 'a'].every(x => x === 'a')); // true
// some
console.log([ , 'a'].some(x => x !== 'a')); // false
// 【总结】以上4个方法都会忽略空位
// map --> 跳过空位,但会保留这个值
console.log([ , 'a'].map(x => 1)); // [, 1]
// join
console.log([, 'a', undefined, null].join('#')); // ” # a## "
// toString
console.log([, 'a', undefined, null].toString()); // ',a,,'
// 【总结】以上这2个方法会将空位视为undefined,而undefined 和 null 会被处理为空字符串
// ES6明确将空位转为“undefined”,不会忽略空位
// (1) Array.from()
console.log( Array.from(['a', , 'v']));
// (2) 扩展运算符(...)
console.log([...[1, 2, , 3]]);
// (3) copyWithin()会将空位一起赋值
console.log([,'a','v', ,].copyWithin(2, 0));
// (4) fill()会将空位视为正常的数组位置
console.log(new Array(3).fill('a')); // ["a", "a", "a"]
// (5) for...of循环也会遍历空位
let arr = [, ,];
for (let i of arr){
console.log(1);
}
// (6) 数组实例的entries()、keys()和values(), find() and findIndex()
console.log([...[, 'a'].entries()]); // [[0 ,u ndefined ], [1 ,” a ”]]
console.log([...[, 'a'].keys()]); // [0, 1]
console.log([...[, 'a'].values()]); // [undefined ,” a ”]
console.log([, 'a'].find(x => true)); // undefined
console.log([, 'a'].findIndex(x => true)); // 0
// 【总结】 由于空位的处理规则非常不统一,所以建议避免出现空位!!!
</script>
</body>
</html>