遇到数组问题你还在只会使用for循环吗?这些操作使你代码更为简洁!

352 阅读5分钟

1.Array.isArray() 用于确定传递的值是否是一个 Array。

Array.isArray([1, 2, 3]);  
// true
Array.isArray({foo: 123}); 
// false
Array.isArray("foobar");   
// false
Array.isArray(undefined);  
// false

2. concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// ["a", "b", "c", "d", "e", "f"]

// ES6写法
console.log([...array1, ...array2])
// ["a", "b", "c", "d", "e", "f"]

3.判断一个数组是否满足条件

3.1 every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。

注意:若收到一个空数组,此方法在一切情况下都会返回 true。

const array1 = [1, 30, 39, 29, 10, 13];

// 判断数组是否中所有元素是否全部小于 40
const isAll = array1.every(item => item < 40)
console.log(isAll)
// true

3.2 some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回一个布尔值。

注意:如果用一个空数组进行测试,在任何情况下它返回的都是false。

const array1 = [1, 30, 39, 29, 10, 13];

// 判断数组是否中含有小于10的数
const isAll1 = array1.some(item => item < 10)
console.log(isAll1)
// true

// 判断数组是否中含有大于40的数
const isAll2 = array1.some(item => item > 40)
console.log(isAll2)
// false

3.3 includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

注意:对象数组不能使用includes方法来检测。

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

3.4 indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1
const obj1 = { a: 1 }
const obj2 = { a: 2 }
const arr = [obj1, obj2, 3]

console.log(arr.indexOf(obj2))
// 1

3.5 find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

const inventory = [
    {name: 'apples', id: 1},
    {name: 'bananas', id: 2},
    {name: 'cherries', id: 3}
];

console.log(inventory.find(item => item.id === 2)); // { name: 'bananas', id: 2 }
console.log(inventory.find(item => item.id === 4)); // undefined

3.6 findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。

const inventory = [
    {name: 'apples', id: 1},
    {name: 'bananas', id: 2},
    {name: 'cherries', id: 3}
];

console.log(inventory.findIndex(item => item.id === 2)); // 1
console.log(inventory.findIndex(item => item.id === 4)); // -1

3.7 filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// ["exuberant", "destruction", "present"]

4.其他数组操作

4.1 forEach() 方法对数组的每个元素执行一次提供的函数。

var array1 = ['a', 'b', 'c'];

array1.forEach((item,index) => {
    console.log(item, index)
});

// "a" 0
// "b" 1
// "c" 2

4.2 join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。

var 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"

4.3 map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

const inventory = [
    {name: 'apples', id: 1},
    {name: 'bananas', id: 2},
    {name: 'cherries', id: 3}
];

const map1 = inventory.map(item => {
    return {
        label: item.name,
        value: item.id
    }
})

console.log(map1)
//  Array [Object { label: "apples", value: 1 }, Object { label: "bananas", value: 2 }, Object { label: "cherries", value: 3 }]

4.4 pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。

var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

4.5 push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。

4.6 shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

4.7 reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

4.8 reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。

var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']

var reversed = array1.reverse(); 
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']

/* Careful: reverse is destructive. It also changes
the original array */ 
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']

4.9 slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

var 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"]

4.10 splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

var 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']

4.11 sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的

由于它取决于具体实现,因此无法保证排序的时间和空间复杂性。

var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

更多其他内容请查看 javascript | MDN