2021.04.27(数组实例的 find() 和 findIndex()、数组实例的 fill()、数组实例的 entries(),keys() 和 values())
数组实例的 find() 和 findIndex()
数组实例的 find 方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组
成员依次执行该回调函数,直到找出第一个返回值为 true 的成员,然后返回该成员。如果没有符合
条件的成员,则返回 undefined 。
1. [1, 4, -5, 10].find((n) => n < 0) 2. // -5
上面代码找出数组中第一个小于 0 的成员。
1. [1, 5, 10, 15].find(function(value, index, arr) { 2. return value > 9; 3. }) // 10
上面代码中, find 方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。
数组实例的 findIndex 方法的用法与 find 方法非常类似,返回第一个符合条件的数组成员的位
置,如果所有成员都不符合条件,则返回 -1 。
1. [1, 5, 10, 15].findIndex(function(value, index, arr) { 2. return value > 9; 3. }) // 2
这两个方法都可以接受第二个参数,用来绑定回调函数的 this 对象。
1. function f(v){ 2. return v > this.age; 3. } 4. let person = {name: 'John', age: 20}; 5. [10, 12, 26, 15].find(f, person); // 26
上面的代码中, find 函数接收了第二个参数 person 对象,回调函数中的 this 对象指
向 person 对象。
另外,这两个方法都可以发现 NaN ,弥补了数组的 indexOf 方法的不足。
1. [NaN].indexOf(NaN) 2. // -1 3. 4. [NaN].findIndex(y => Object.is(NaN, y)) 5. // 0
上面代码中, indexOf 方法无法识别数组的 NaN 成员,但是 findIndex 方法可以借
助 Object.is 方法做到。
数组实例的 fill()
fill 方法使用给定值,填充一个数组。
1. ['a', 'b', 'c'].fill(7) 2. // [7, 7, 7] 3. 4. new Array(3).fill(7) 5. // [7, 7, 7]
上面代码表明, fill 方法用于空数组的初始化非常方便。数组中已有的元素,会被全部抹去。
fill 方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
1. ['a', 'b', 'c'].fill(7, 1, 2) 2. // ['a', 7, 'c']
上面代码表示, fill 方法从 1 号位开始,向原数组填充 7,到 2 号位之前结束。
注意,如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象。
1. let arr = new Array(3).fill({name: "Mike"}); 2. arr[0].name = "Ben"; 3. arr 4. // [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}] 5. 6. let arr = new Array(3).fill([]); 7. arr[0].push(5); 8. arr 9. // [[5], [5], [5]]
数组实例的 entries(),keys() 和 values()
ES6 提供三个新的方法—— entries() , keys() 和 values() ——用于遍历数组。它们都返回一
个遍历器对象(详见《Iterator》一章),可以用 for...of 循环进行遍历,唯一的区别
是 keys() 是对键名的遍历、 values() 是对键值的遍历, entries() 是对键值对的遍历。
1. for (let index of ['a', 'b'].keys()) { 2. console.log(index); 3. } 4. // 0 5. // 1 6. 7. for (let elem of ['a', 'b'].values()) { 8. console.log(elem); 9. } 10. // 'a' 11. // 'b' 12. 13. for (let [index, elem] of ['a', 'b'].entries()) { 14. console.log(index, elem); 15. } 16. // 0 "a" 17. // 1 "b"
如果不使用 for...of 循环,可以手动调用遍历器对象的 next 方法,进行遍历。
1. let letter = ['a', 'b', 'c']; 2. let entries = letter.entries(); 3. console.log(entries.next().value); // [0, 'a'] 4. console.log(entries.next().value); // [1, 'b'] 5. console.log(entries.next().value); // [2, 'c']
2021-04-27 11:16:52

浙公网安备 33010602011771号