《ES6标准入门(第3版)》学习笔记29:chapter_8 数组的扩展之数组的空位

这是该系列的第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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值