这些方法遍历数组的每个元素,可以对元素进行操作或返回新数组。
forEach()方法用于遍历数组,对数组的每个元素执行一次给定的函数,会修改原数组。
const arr = ['a','b','c'];
//用来遍历数组
arr.forEach(function(item,index){//第一个参数为元素项,第二个参数为索引
console.log(item,index);
})
//output:'a' 0
//output:'b' 1
//output:'c' 2
every()方法测试一个数组内的元素是否都符合指定函数的测试,返回的是一个布尔值。
const arr1 = [1, 2, 3, 4];
//例子1:
const isRequire = function (item) { return item < 5 } //定义一个指定的函数测试
//每一个元素都符合条件返回true,有一个不满足就返回false
console.log(arr1.every(isRequire));//true
//例子2:
const isRequire1 = function (item) { return item < 4 }
console.log(arr1.every(isRequire1));//false
some()测试数组中的元素有一个元素符合指定函数的测试就返回true,否则返回false。不会修改原数组。
const arr1 = [1, 2, 3, 4];
//例子1:
const isRequire = function (item) { return item < 5 } //定义一个指定的函数测试
//每一个元素都符合条件返回true,有一个不满足就返回false
console.log(arr1.some(isRequire));//true
map()方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
const arr2 = [1, 2, 3, 4, 5];
//item为正在处理的元素,index当前处理元素的索引,调用map()的数组本身
const res = arr2.map(function (item, index,array) {
return item * 2
})
console.log(res);
filter()
const arr3 = [1,2,3];
//filter方法,把数组里符合条件的元素保留,不符合的删去,返回的是一个数组
//如果没有符合条件的,最后一个结果还是一个数组
var res1 = arr3.filter(function (currentValue, index, array) {
return currentValue> 2 // [3]
})
console.log(res1);
reduce()方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const num = 0; //定义变量为累加的初始值
const sum = array1.reduce(
function (accumulator, currentValue) {
return accumulator + currentValue;
},
num
);
console.log(sum);
// Expected output: 10
reduceRight()方法对累加器(accumulator)和数组的每个值(按从右到左的顺序)应用一个函数,并使其成为单个值。可以对比reduce( )
这些方法将数组元素转换为新的形式或结构,并返回新数组。
concat()方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]
slice()方法返回一个新的数组对象,这一对象是一个由 start 和 end 决定的原数组的(包括 start,不包括 end),其中 start 和 end 代表了数组元素的索引。原始数组不会被改变
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
splice()方法就地移除或者替换已存在的元素和/或添加新的元素
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
flat()方法创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]
const arr2 = [0, 1, [2, [3, [4, 5]]]];
console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]
flatMap()方法对数组中的每个元素应用给定的回调函数,然后将结果展开一级,返回一个新数组。它等价于在调用 map()方法后再调用深度为 1 的 flat() 方法(arr.map(...args).flat()),但比分别调用这两个方法稍微更高效一些。
const arr1 = [1, 2, 1];
const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));
console.log(result);
// Expected output: Array [1, 2, 2, 1]
这些方法用于查找数组中的元素,并可能返回元素的索引或布尔值。
indexOf()方法返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// Expected output: 1
// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4
console.log(beasts.indexOf('giraffe'));
// Expected output: -1
lastIndexOf()方法返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从 fromIndex 开始向前搜索数组。
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
console.log(animals.lastIndexOf('Dodo'));
// Expected output: 3
console.log(animals.lastIndexOf('Tiger'));
// Expected output: 1
find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found);
// Expected output: 12
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// Expected output: 3
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// Expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// Expected output: true
console.log(pets.includes('at'));
// Expected output: false
at( )方法接收一个整数值并返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。
const array1 = [5, 12, 8, 130, 44];
let index = 2;
console.log(`An index of ${index} returns ${array1.at(index)}`);
// Expected output: "An index of 2 returns 8"
index = -2;
console.log(`An index of ${index} returns ${array1.at(index)}`);
// Expected output: "An index of -2 returns 130"
这些方法用于改变数组元素的顺序。
sort()方法就地对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]
reverse()方法就地反转数组中的元素,并返回同一数组的引用。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。换句话说,数组中的元素顺序将被翻转,变为与之前相反的方向。要在不改变原始数组的情况下反转数组中的元素,使用 。
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Expected output: "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);
// Expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]
这些方法用于修改数组的内容,包括添加和删除元素。
push()方法将指定的元素添加到数组的末尾,并返回新的数组长度。
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// Expected output: "tomato"
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]
shift()方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
unshift()方法将指定元素添加到数组的开头,并返回数组的新长度。
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// Expected output: 5
console.log(array1);
// Expected output: Array [4, 5, 1, 2, 3]
splice()方法移除或者替换已存在的元素和/或添加新的元素。
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
这些方法用于创建数组的迭代器,可以用于遍历数组。
keys()方法返回一个新的对象,其中包含数组中每个索引的键。
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// Expected output: 0
// Expected output: 1
// Expected output: 2
values()方法返回一个新的对象,该对象迭代数组中每个元素的值。
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
entries()方法返回一个新的对象,该对象包含数组中每个索引的键/值对。
const array1 = ['a', 'b', 'c'];
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// Expected output: Array [0, "a"]
console.log(iterator1.next().value);
// Expected output: Array [1, "b"]
这些方法执行特定的操作,如合并数组或检查数组是否包含特定元素。
join()方法将一个数组(或一个)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// Expected output: "Fire,Air,Water"
console.log(elements.join(''));
// Expected output: "FireAirWater"
console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"
toString()方法返回一个字符串,表示指定的数组及其元素。
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// Expected output: "1,2,a,1a"
toLocaleString()方法返回一个字符串,表示数组中的所有元素。每个元素通过调用它们自己的 toLocaleString 方法转换为字符串,并且使用特定于语言环境的字符串(例如逗号“,”)分隔开。
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);
// Expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
随着 ECMAScript 标准的更新,一些新的方法被添加到数组中。
copyWithin()方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。fill()方法用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引(默认为 array.length)内的全部元素。它返回修改后的数组。entries() (在ES7中明确为数组方法) 方法返回一个新的对象,该对象包含数组中每个索引的键/值对。keys() (在ES7中明确为数组方法) 方法返回一个新的对象,其中包含数组中每个索引的键。values() (在ES7中明确为数组方法) 方法返回一个新的对象,该对象迭代数组中每个元素的值。flat() (在ES2019中引入) 方法创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中。flatMap() (在ES2019中引入) 方法对数组中的每个元素应用给定的回调函数,然后将结果展开一级,返回一个新数组。它等价于在调用 方法后再调用深度为 1 的 方法(arr.map(...args).flat()),但比分别调用这两个方法稍微更高效一些。因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- gamedaodao.net 版权所有 湘ICP备2024080961号-6
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务