业务中关于数组的常用场景方法总结

业务中,我们通常需要结合业务来整理一些数据,有一些常用的处理技巧

使用 arr1.push(...arr2) 可比 arr1 = arr1.concat(arr2) 节省时间

filter过滤

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

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

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

concat

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

console.log(array1.concat(array2));
// es6中
console.log(…array1…array2)

join

var elements = ['Fire', 'Wind', 'Rain'];

console.log(elements.join());
// expected output: Fire,Wind,Rain

console.log(elements.join(''));
// expected output: FireWindRain

console.log(elements.join('-'));
// expected output: Fire-Wind-Rain

forEach

遍历子项的时候执行提供的函数,并不改变数组
var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  element+ '2222'
  console.log(element+ '2222');
});
console.log(array1)

every

function isBelowThreshold(currentValue) {
  return currentValue < 40;
}

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

console.log(array1.every(isBelowThreshold));

slice

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, -1));
// expected output: Array ["bison", "camel", "duck", "elephant"]

splice方法

通过删除现有元素和/或添加新元素来更改原数组的内容
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May’]
splice方法使用deleteCount参数来控制是删除还是添加:
start参数是必须的,表示开始的位置(从0计数),如:start=0从第一个开始;start>= array.length-1表示从最后一个开始。
①、从start位置开始删除[start,end]的元素。
array.splice(start)
②、从start位置开始删除[start,Count]的元素。
array.splice(start, deleteCount)    
③、从start位置开始添加item1, item2, ...元素。
array.splice(start, 0, item1, item2, ...)   

遍历数组最严谨的方式

for (const [i, v] of arr.entries()) {
    console.log(i, v);
}

indexOf

检测数组是否存在某个元素

var 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('duck'));