JavaScript 数组方法

    技术2026-01-17  5

    JavaScript 数组方法

    文章目录

    JavaScript 数组方法forEach()方法map()方法filter() 方法

    forEach()方法

    forEach() 方法是遍历数组,把遍历出来的每一项交给回调函数.

    语法结构:

    arr.forEach(function (item, index) { }); arr:一个数组参数: item:数组里面的值index:每一个值对应的索引 let arr = [10, 20, 30, 40]; arr.forEach(function (item, index) { console.log(item, index); }); // 10 0 // 20 1 // 30 2 // 40 3

    map()方法

    map() 方法是遍历数组的,有返回值 语法结构:

    arr.map(function (item, index) { }); arr:一个数组参数: item:数组里面的值index:每一个值对应的索引 返回值:一个新数组 ` let arr = [10, 20, 30, 40]; let arrNew = arr.map(function (item, index) { return item * item; }); console.log(arrNew); // [ 100, 400, 900, 1600 ]

    filter() 方法

    filter() 方法会一个新的数组,新的数组中的元素是通过检查后符合条件的元素. 语法结构:

    arr.filter(function (item, index) { }); arr:一个数组参数: item:数组里面的值index:每一个值对应的索引 返回值:一个符合条件的新数组 let arr = [10, 20, 11, 21, 30, 31, 34, 56, 67]; let arrNew = arr.filter(function (item, index) { return item % 2 == 0; }); console.log(arrNew); // [ 10, 20, 30, 34, 56 ]
    Processed: 0.029, SQL: 9