16. 数组的拓展方法
1. keys
- // 例子 16-1
- var arr = ["a", , "c"];
- var sparseKeys = Object.keys(arr);
- console.log(sparseKeys); // ['0', '2']
- var denseKeys = [...arr.keys()];
- console.log(denseKeys); // [0, 1, 2]
2. entries
- // 例子 16-2
- var arr = ["a", "b", "c"];
- var iterator = arr.entries();
- for (let e of iterator) {
- console.log(e);
- }
3. values
- // 例子 16-3
- let arr = ['w', 'y', 'k', 'o', 'p'];
- let eArr = arr.values();
- for (let letter of eArr) {
- console.log(letter);
- }
4. includes
- // 例子 16-4
- // bad
- function test(fruit) {
- if (fruit == 'apple' || fruit == 'strawberry') {
- console.log('red');
- }
- }
- // good
- function test(fruit) {
- const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
- if (redFruits.includes(fruit)) {
- console.log('red');
- }
- }
5. find
- // 例子 16-5
- var inventory = [
- {name: 'apples', quantity: 2},
- {name: 'bananas', quantity: 0},
- {name: 'cherries', quantity: 5}
- ];
- function findCherries(fruit) {
- return fruit.name === 'cherries';
- }
- console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
6. findIndex
- // 例子 16-6
- function isPrime(element, index, array) {
- var start = 2;
- while (start <= Math.sqrt(element)) {
- if (element % start++ < 1) {
- return false;
- }
- }
- return element > 1;
- }
- console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
- console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
更多的就不列举了。