通过示例解释所有 JavaScript 数组方法


通过示例解释所有 JavaScript 数组方法

文章插图
作为一名程序员,我们的工作是写有效的代码 , 但是仅仅写有效的代码,这还不够 。如果想成为优秀的程序员,我们还需要编写可维护和可扩展的代码 。
JAVAScript为我们提供了很多可以用来处理数组的util方法 。今天,就让我们一起来看看这 42 个数组方法 。1. at获取特定索引处的元素 。负索引表示从末尾开始计数(例如:-1 是最后一个元素) 。const names = ["Jhon", "Bob", "Alice", "Joe"];const nameAtIndex1 = names.at(1);const nameAtLastIndex = names.at(-1);const nameAtBeforeLastIndex = names.at(-2);const nameAtNonExistingIndex = names.at(10);console.log(nameAtIndex1); // Output : Bobconsole.log(nameAtLastIndex); // Output : Joeconsole.log(nameAtBeforeLastIndex); // Output : Aliceconsole.log(nameAtNonExistingIndex); // Output : undefined2.concat
将给定的数组元素添加到调用者数组的末尾 。
const manNames = ["Jhon", "Bob"];const womanNames = ["Alice"];const nameConcatenation = manNames.concat(womanNames);console.log(nameConcatenation); // Output : ["Jhon", "Bob", "Alice"]3. copyWithin
将给定开始索引和结束索引之间的元素复制到目标索引 。
负索引表示从最后一个开始计数(例如:-1 是最后一个元素) 。
let letters = [];// Copy to index 1, all elements form the index 3 to index 5 not included ("d" and "e")letters = ["a", "b", "c", "d", "e", "f", "g", "h"];letters.copyWithin(1, 3, 5);console.log(letters);// Output : ["a", "d", "e", "d", "e", "f", "g", "h"]// Copy to index 1, all elements form the index 3 to end ("d", "e", "f", "g" and "h")letters = ["a", "b", "c", "d", "e", "f", "g", "h"];letters.copyWithin(1, 3);console.log(letters);// Output : ["a", "d", "e", "f", "g", "h", "g", "h"]// Copy to index -7 (equivalent to 2), all elements from the index -6 (equivalent to 3) to index 5 not included ("d" and "e")letters = ["a", "b", "c", "d", "e", "f", "g", "h"];letters.copyWithin(-7, -6, 5);console.log(letters);// Output : ["a", "d", "e", "d", "e", "f", "g", "h"]4.  entries
返回一个迭代器,其中,包含每个数组元素的索引/值对的数组 。
const letters = ["a", "b"];const iterator1 = letters.entries();console.log(iterator1.next().value); // Output [0, 'a']console.log(iterator1.next().value); // Output : [0, 'b']console.log(iterator1.next().value); // Output : undefined5. every
检查所有数组元素是否验证给定条件并返回 true 。否则,返回 false 。
const numbers = [10, 15, 20, 25, 30];const isAllNumbersBelow40 = numbers.every((number) => number < 40);console.log(isAllNumbersBelow40); // Output : trueconst isAllNumbersBelow20 = numbers.every((number) => number < 20);console.log(isAllNumbersBelow20); // Output : false6. fill
按给定值从开始索引到结束索引填充数组 。
负索引表示从最后一个开始计数(例如:-1 是最后一个元素) 。
let numbers = [];/** Fill 0 on numbers start at index 1 to index 4 not included (3 elements) */numbers = [1, 1, 1, 1, 1];numbers.fill(0, 1, 4);console.log(numbers);// Output : [1, 0, 0, 0, ]/** Fill 0 on numbers start at index 1 to the end (4 elements) */numbers = [1, 1, 1, 1, 1];numbers.fill(0, 1);console.log(numbers);// Output : [1, 0, 0, 0, 0]/** Fill 0 on all numbers */numbers = [1, 1, 1, 1, 1];numbers.fill(0);console.log(numbers);// Output : [0, 0, 0, 0, 0]/** Fill 0 on numbers start at index -4 (equivalent to 2) to index -1 (equivalent to 4) not included (3 elements) */


推荐阅读