Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array methods in ECMAScript 6 #4

Closed
mqy1023 opened this issue Sep 15, 2016 · 0 comments
Closed

Array methods in ECMAScript 6 #4

mqy1023 opened this issue Sep 15, 2016 · 0 comments

Comments

@mqy1023
Copy link
Owner

mqy1023 commented Sep 15, 2016

1、Array.prototype.find
快速获取到第一个匹配值

let numbers = [1, 2, 3];
let oddNumber = numbers.find((x) => x % 2 == 1);
console.log(oddNumber); // 1

2、Array.prototype.findIndex
返回第一个匹配值的下标

let people = ['jamie', 'jack', 'isaac'];
let jackIndex = people.findIndex((x) => x === 'jack');
console.log(jackIndex); // 1

3、Array.prototype.entries
返回一个数组迭代器(Array Iterator), that can be used to loop through the array’s keys and values. entries will return an array of arrays, where each child array is an array of [index, value].

let people = ['jamie', 'jack', 'isaac'];
let entries = people.entries();
console.log(entries.next().value); // [0, 'jamie']
console.log(entries.next().value); // [1, 'jack']
console.log(entries.next().value); // [2, 'isaac']

We can also use the spread operator to get back an array of the entries in one go:

let people = ['jamie', 'jack', 'isaac'];
let entries = people.entries();
console.log([...entries]); // [[0, 'jamie'], [1, 'jack'], [2, 'isaac']]

4、Array.from

Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']

Array.from([1, 2, 3]); // [1, 2, 3]

let namesSet = new Set(['jamie', 'jack']);
Array.from(namesSet); // ['jamie', 'jack']

from can also take a second argument, which is a map function to be applied to each element:

Array.from([1, 2, 3], (x) => x * x); // [1, 4, 9]

Because the method can take array like objects, we can use it to generate arrays of values too:

Array.from({ length: 4 }, (val, key) => key); // [0, 1, 2, 3]

Each time the mapping function gets called, the val argument will be undefined, as this object has no actual values, but the key argument will be 0, then 1 and so on. This lets us generate arrays of numbers, but we can also return whatever we’d like from the mapping function:

Array.from({ length: 2 }, () => 'jack'); // ['jack', 'jack']

5、Array.map
返回新的数组

const arr = ['1', '2', '3'].map(() => false);
console.log(arr); //[false, false, false]

原文链接

@mqy1023 mqy1023 changed the title 【收藏】理解redux系列文章 Array methods in ECMAScript 6 Sep 20, 2016
@mqy1023 mqy1023 closed this as completed Oct 7, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant