16. 数组的拓展方法

1. keys

  1. // 例子 16-1
  2.  
  3. var arr = ["a", , "c"];
  4.  
  5. var sparseKeys = Object.keys(arr);
  6. console.log(sparseKeys); // ['0', '2']
  7.  
  8. var denseKeys = [...arr.keys()];
  9. console.log(denseKeys); // [0, 1, 2]

2. entries

  1. // 例子 16-2
  2.  
  3. var arr = ["a", "b", "c"];
  4. var iterator = arr.entries();
  5.  
  6. for (let e of iterator) {
  7. console.log(e);
  8. }

3. values

  1. // 例子 16-3
  2.  
  3. let arr = ['w', 'y', 'k', 'o', 'p'];
  4. let eArr = arr.values();
  5.  
  6. for (let letter of eArr) {
  7. console.log(letter);
  8. }

4. includes

  1. // 例子 16-4
  2.  
  3. // bad
  4. function test(fruit) {
  5. if (fruit == 'apple' || fruit == 'strawberry') {
  6. console.log('red');
  7. }
  8. }
  9.  
  10. // good
  11. function test(fruit) {
  12. const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  13. if (redFruits.includes(fruit)) {
  14. console.log('red');
  15. }
  16. }

5. find

  1. // 例子 16-5
  2.  
  3. var inventory = [
  4. {name: 'apples', quantity: 2},
  5. {name: 'bananas', quantity: 0},
  6. {name: 'cherries', quantity: 5}
  7. ];
  8.  
  9. function findCherries(fruit) {
  10. return fruit.name === 'cherries';
  11. }
  12.  
  13. console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

6. findIndex

  1. // 例子 16-6
  2.  
  3. function isPrime(element, index, array) {
  4. var start = 2;
  5. while (start <= Math.sqrt(element)) {
  6. if (element % start++ < 1) {
  7. return false;
  8. }
  9. }
  10. return element > 1;
  11. }
  12.  
  13. console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
  14. console.log([4, 6, 7, 12].findIndex(isPrime)); // 2

更多的就不列举了。