Array Methods

2018-05-29  本文已影响0人  小菜鸟Soul

map

示例代码
const numbers = [0, 1, 2, 3, 4, 5, 6];
const doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]

filter

示例代码
const numbers = [0, 1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]

reduce

redce方法有两个参数
callback参数
示例代码
const numbers = [0, 1, 2, 3, 4, 5, 6];
const sum = numbers.reduce((prev, next) => prev + next, 0); // 21
详解:

第一次迭代步骤
prev = 0 因为我们传入0作为第二个参数
next = 0 取元素中的第一个元素。
函数返回 prev + next - > 0 + 0 - > 0

第二个迭代步骤
prev = 0 因为它是在上一次迭代步骤中函数返回的值
next = 1 取元素中的第二个元素
函数返回 prev + next - > 0 + 1 - > 1

第三个迭代步骤
prev = 1 因为它是在上一次迭代步骤中函数返回的值
next = 2 取元素中的第三个元素
函数返回 prev + next - > 1 + 2 - > 3

第四次迭代步骤
prev = 3 因为它是在上一次迭代步骤中函数返回的值
next = 3 取元素中的第四个元素
函数返回 prev + next - > 3 + 3 - > 6

[...]在最后的迭代步骤
prev = 15 因为它是在上一次迭代步骤中函数返回的值
next = 6 所述的最后一个元素数阵列
函数返回 prev + next - > 15 + 6 - > 21
由于这是最后一次迭代步骤,.reduce返回21。

copyWithin

参数
示例代码
let arr=[1, 2, 3, 4, 5];
let numbers=arr.copyWithin(0, 3, 4) // [4, 2, 3, 4, 5]

keys

示例代码
let arr = ["a", "b", "c"];
let iterator = arr.keys();

console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

values

示例代码
let arr = ["a", "b", "c"];
let iterator = arr.values();

console.log(iterator.next()); // { value: "a", done: false }
console.log(iterator.next()); // { value: "b", done: false }
console.log(iterator.next()); // { value: "c", done: false }
console.log(iterator.next()); // { value: undefined, done: true }

entries

示例代码
let arr = ["a", "b", "c"];
let iterator = arr.entries();

console.log(iterator.next()); // { value: [0, "a"], done: false }
console.log(iterator.next()); // { value: [1, "b"], done: false }
console.log(iterator.next()); // { value: [2, "c"], done: false }
console.log(iterator.next()); // { value: undefined, done: true }

includes

示例代码
let arr=["a", "b", "c"];
arr.includes("a"); // true
arr.includes("d"); // false

扩展运算符

扩展运算符...已与ES6一起引入,用于将迭代元素(如数组)扩展到多个元素可以放置的位置。

示例代码

数组:

const arr1=["a", "b", "c"];
const arr2=[...arr1, "d","e","f"]; // ["a", "b", "c", "d", "e", "f"]

对象:

let  obj1={name:"Nick", age:16, sex:"man"};
let {name, ...args}=obj1;
console.log(name); // "Nick"
console.log(args); // {age:16, sex:"man"}
obj1={...obj1, age:20};
console.log(obj1); // {name:"Nick", age:20, sex:"man"}

函数:

function myFunc(x, y, ...params) {
    console.log(x);
    console.log(y);
    console.log(params);
}

myFunc("a", "b", "c", "d", "e", "f");
// "a"
// "b"
// [ "c", "d", "e", "f" ]
参考资料
上一篇下一篇

猜你喜欢

热点阅读