ECMAScript学习(二)Array数组方法

Map集合

格式:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
          // Return element for new_array
}[, thisArg])

返回值说明

The map() method creates a new array with the results of calling a provided function on every element in the calling array.
该方法会返回一个同原数组长度一样的一个新数组,数组中的每一项,就是函数调用后的结果
注意: map() 不会对空数组进行检测。
注意:map() 不会改变原始数组。

使用

let arr = [1, 2, 3, 4, 5, 6, 7];
let a = arr.map((item, index,arr) => {
   console.log(arr);//(7) [1, 2, 3, 4, 5, 6, 7]
   return item * 2;
});
console.log(a);//(7) [2, 4, 6, 8, 10, 12, 14]

filter函数

形式

var newArray = arr.filter(callback(element[, index[, array]])
[, thisArg])

返回值说明:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。

实例

let arr = [1, 2, 3, 4, 5, 6, 7];
let a = arr.filter((item, index, arr) => {
   return item > 3;
});
console.log(a);//(4) [4, 5, 6, 7]

arr.every

定义

arr.every(callback(element[, index[, array]])[, thisArg])

返回值说明

The every() method tests whether all elements in the array pass the test implemented by the provided function.
数组中的每一项运行该函数,如果每一项的函数都返回true,则该方法返回真。
every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。
every() 方法使用指定函数检测数组中的所有元素:
(1)如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
(2)如果所有元素都满足条件,则返回 true。
注意: every() 不会对空数组进行检测。
注意: every() 不会改变原始数组。

实例

let arr = [1, 2, 3, 4, 5, 6, 7];
let a = arr.every(function(item) {
   return item > 1;
});
console.log(a);//false

arr.some()

定义

arr.some(callback[, thisArg])

返回值

数组中的每一项,运行给定函数,只要有一项返回真,那么就返回真。
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组。

实例

let arr = [1, 2, 3, 4, 5, 6, 7];
let a = arr.some(item => item > 6);
console.log(a);//true

arr.reduce()

归并函数

定义

arr.reduce(callback[, initialValue])

返回值说明

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。

实例

let arr = [1, 2, 3, 4, 5];
let a = arr.reduce(function(prev, item, index, arr) {
  return prev + item;
});
console.log('最终结果是:' + a);//最终结果是:15

let a = arr.reduce(function(prev, item, index, arr) {
    return prev + item;
}, 10);
console.log('最终结果是:' + a);//最终结果是:25

arr.filter()

定义

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

返回值说明

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。

实例

数组去重

let arr = [2, 2, 4, 2, 1, 4, 2, 2, 2, 24, 4];
let a = arr.filter(
(item, index, arr) => arr.indexOf(item) === index
);
console.log(a);//(4) [2, 4, 1, 24]

猜你喜欢

转载自blog.csdn.net/WeiAiGeWangFeiYuQing/article/details/84262276
今日推荐