concat()
作用:合并两个或多个数组
形式:数组1. concat
(数组2,数组3…)
是否改变原数组:不会
例子:
var num1 = [1, 2, 3],
num2 = [4, 5, 6],
num3 = [7, 8, 9];
var nums = num1.concat(num2, num3);
console.log(nums);// [1, 2, 3, 4, 5, 6, 7, 8, 9]
every()
作用:测试一个数组内的所有元素是否都能通过某个指定函数的测试
返回值:布尔值
例子:
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); //false
[12, 54, 18, 130, 44].every(isBigEnough); //true
fill()
作用:用一个固定值填充一个数组中从起始索引到终止索引内的全部元素
例子:
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4]
filter()
作用:创建一个新数组, 其包含通过所提供函数实现的测试的所有元素
注意:需要回调函数
例子:
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
alert(filtered)// [12, 130, 44]
find()
作用:返回数组中满足提供的测试函数的第一个元素的值
没有:返回 undefined
例子:(查找质数)
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].find(isPrime)); // undefined,
console.log([4, 5, 8, 12].find(isPrime)); // 5
findIndex()
作用:返回数组中满足提供的测试函数的第一个元素的索引。
没有:返回-1
例子:
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
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
forEach()
作用:对数组的每个元素执行一次给定的函数。(遍历数组)
例子:
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
// 注意索引 2 被跳过了,因为在数组的这个位置没有项
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
includes()
作用:判断一个数组是否包含一个指定的值
返回值:布尔值
例子:
var arr = ['a', 'b', 'c'];
arr.includes('c', 3); // false
arr.includes('c', 100); // false