• 数组forEach函数


    forEach()遍历注意事项:

    1.未被设置的元素不会被遍历到

    var a = [1, 2, 3, 4];
    a[6] = 10;
    a.forEach(function (value, index) {
        console.log(value);//1,2,3,4,10
    });
    console.log(a);//[1,2,3,4,empty*2,10]
    var a = [1, 2, "", 4];
    a.forEach(function (value, index) {
        console.log(value);//1,2,"",4,
    });
    console.log(a);//[1,2,"",4]

    空元素能被遍历到

    var a = [1, 2, undefined, 4];
    a.forEach(function (value, index) {
        console.log(value);//1,2,undefined,4,
    });
    console.log(a);//[1,2,undefined,4]

    undefined能被遍历到

    2.新添加的元素不会被遍历到

    var a = [1, 2, 3, 4];
    a.forEach(function (value, index) {
        if (index == 0) a[6] = 10;
        console.log(value);//1,2,3,4
    });
    console.log(a);//[1,2,3,4,empty*2,10]

     3.遍历时,删除的元素不会被遍历到

    var a = [1, 2, 3, 4];
    a.forEach(function (value, index) {
        if (index == 2) delete a[3];
        console.log(value);//1,2,4
    });
    console.log(a);//[1,2,3,empty]

    4.遍历时,用shift()方法删除元素,则会对后续遍历产生影响 

    var a = [1, 2, 3, 4];
    a.forEach(function (value, index) {
        if (index == 1) a.shift();
        console.log(value);//1,2,4
    });
    console.log(a);//[2,3,4]

     shift()函数会重新调整数组长度,导致原下标对应的值发生改变

    5.后续没有被遍历到的元素能修改值

    var a = [1, 2, 3, 4];
    a.forEach(function (value, index) {
        if (index == 0) a[1] = 10;
        console.log(value);//1,10,3,4
    });
    console.log(a);//[1,10,3,4]

      6.已经遍历过得项,再修改值,则来不及了

    var a = [1, 2, 3, 4];
    a.forEach(function (value, index) {
        if (index == 2) a[1] = 10;
        console.log(value);//1,2,3,4
    });
    console.log(a);//[1,10,3,4]
  • 相关阅读:
    nrm安装与使用
    10、ReactJs基础知识10--组件组合 vs 继承
    9、ReactJs基础知识09--状态提升
    8、ReactJs基础知识08--表单
    7、ReactJs基础知识07--列表渲染 & Key
    6、ReactJs基础知识06--条件渲染
    5、ReactJs基础知识05--事件处理
    L2-030 冰岛人 (25分)
    进阶实验5-3.4 迷你搜索引擎 (35分)
    进阶实验2-3.4 素因子分解 (20分)
  • 原文地址:https://www.cnblogs.com/bibiafa/p/9391190.html
Copyright © 2020-2023  润新知