zoukankan      html  css  js  c++  java
  • 数组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]
  • 相关阅读:
    1. shiro-用户认证
    Salt 盐值
    使用ajax向后台发送请求跳转页面无效的原因
    @RequestParam和@RequestBody的区别
    JavaSE:Java11的新特性
    JavaSE: Java10的新特性
    JavaSE:Java9 新特性
    JavaSE:Java8新特性
    JavaSE:Java8新特性
    JavaSE:Java8 新特性
  • 原文地址:https://www.cnblogs.com/bibiafa/p/9391190.html
Copyright © 2011-2022 走看看