zoukankan      html  css  js  c++  java
  • 数组迭代

    数组法代是一件很重要的操作,在 ECMAScript 5 之前主要使用 for 语句实现,这种方式不是很方便, 为此 ECMAScript 5 新增了 5 个与迭代相关的方法。 

    1. forEach:为数组中的每个元素调用定义的回调函数。

    2. every:检查定义的回调函数如果每一项都返回true,则返回 true。

    3. some:检查定义的回调函数如果任意一项返回true。返回 true。

    4. map:对数组的每个元素调用定义的回调函数,并返回包含结果的数组。

    5. filter:对数组的每个元素调用定义的回调函数,并返回回调函数为其返回 true 的值的数组。 具体说明如下。

    forEach

    //forEach中可选参数thisArg可以为函数指定this指向,忽略则指向window。(箭头函数无效,仅普通函数)
    let thisArg = {
        name: '熊猫',
        age: 21,
        sex: '女'
    }
    let arr = [1, 2, 3];
    arr.forEach(function(value, index, array){
        console.log(this)   //{name: '熊猫', age: 21, sex: '女'}
        console.log(value)  //123
        console.log(index)  //012
        console.log(array)  //1,2,3
    },thisArg);

    every

    let arr = [1, 2, 3];
    console.log(arr.every(function(value, index, array){
        return value > 2;
    }))  //false

    some

    let arr = [1,2,3];
        console.log(arr.some(function(value, index, array){
        return value > 2;
    }))  //true

    map

    let arr = [1, 2, 3];
    arr = arr.map(function(value, index, array){
        return value + 1;
    });
    console.log(arr);  //2,3,4

    filter

    var arr = [5, "element", 10, "the", true];
    var result = arr.filter(function(value, index, array){
        return (typeof value === 'string');
    });
    document.write(result);   //返回值:["element", "the"]
  • 相关阅读:
    一个页面从输入 URL 到页面加载显示完成,这个过程中都发生了什么?
    210902
    1-2
    1-1
    4
    3
    2
    1
    u编码
    windows java 安装版 控制面板
  • 原文地址:https://www.cnblogs.com/lanshu123/p/10516069.html
Copyright © 2011-2022 走看看