JavaScript 数组方法

76 阅读2分钟

不影响原数组,创建新数组

连接:concat()

arrayObject.concat(arrayX,arrayX,......,arrayX)
  • 浅拷贝

截取:slice()

  • 接收两个参数,start 和 end,用于指定要提取的数组元素的范围
const arr = [1, 2, 3, 4, 5];
const newArray = arr.slice(2, 4);

console.log(newArray); // 输出 [3, 4]
  • 只传递一个参数,表示从指定索引开始一直到数组的末尾
const arr = [1, 2, 3, 4, 5];
const newArray = arr.slice(3);
console.log(newArray); // 输出 [4, 5]
  • 不会修改原始数组,而是返回一个新的数组

  • 省略了参数,或者参数超出了数组的范围,slice() 方法会返回一个空数组

筛选:filter()

  • 不会对空数组进行检测
eg: arr.filter( (item,index,arr) => { return item>18 })
// 32,33,40

map()

  • 不会对空数组进行检测

影响原数组,不会新建新数组

插入: splice()

const numbers = [1, 2, 3, 4, 5]
numbers.splice(2, 2, 'three') // Replace 2 elements starting from index 2
console.log(numbers) // Output: [1, 2, 'three', 5]

排序

reverse()

sort()

// sort
let arr = ['a', 'b', 'd', 'c']
arr.sort(function (a, b) {
  if (a > b) {
    return -1
  } else if (b > a) {
    return 1
  } else {
    return 0
  }
})
// sort
let arr = [1, 5, 3, 7, 6];
arr.sort(function (a, b) {
	return a - b;
})
  • 以数组中字符串长度进行排序
let arr = ['1234', '56', '23980', '234', '7'];
arr.sort(function (a, b) {
	return a.length - b.length;
})
  • 数组中的对象中的某个属性值排序
let arr = [
{name: 'ww', age: 12},
{name: 'gg', age: 8},
{name: 'uu', age: 69}
];
arr.sort(function (a, b) {
	return a.age - b.age;
})

遍历

arr.forEach(item, index, arr)

  • 不会对空数组执行

  • 直接用item=xxx是无法改变原数组

  • 用arr[index]就可以改变原数组

var s = [1,2,3,4];
s.forEach(item=>{
   item = 'a'
});
console.log(s);// ["1", "2", "3", "4"] 未改变原数组

s.forEach((item, index, arr)=>{
   arr[index] = 'b'
})
console.log(s);// ["b", "b", "b", "b"] 改变了原数组
  • 数组里面的子元素是对象时是可以改变对应属性的
var s = [{a:1}, {a:1}];
s.forEach(item=>{
    item = null;
});
console.log(s);//[{a: 1} ,{a: 1}] 未改变原数组
 
s.forEach(item=>{
    item.a = 666;
});
console.log(s) // [{a: 666}, {a: 666}] //改变的原数组里面的对象属性

findIndex

  • 可应用于类数组对象
const numbers = [2, 5, 8, 1, 4, 7]
const evenIndex = numbers.findIndex((element, index) => {
  return element % 2 === 0 && index % 2 === 0
})

console.log(evenIndex) // Output: 2
  • 转换方法:toString() toLocalString() join()

  • 尾操作:pop() push()

  • 首操作: shift() unshift()

    • 改变原始数组
    const arr = [1, 2, 3, 4, 5]; 
    const firstElement = arr.shift(); 
    console.log(firstElement); // 输出 1 
    console.log(arr); // 输出 [2, 3, 4, 5]
    
    const arr = [1, 2, 3, 4, 5];
    const newLength = arr.unshift(0);
    console.log(newLength); // 输出 6
    console.log(arr); // 输出 [0, 1, 2, 3, 4, 5]
    
  • 索引: indexOf()

  • 迭代方法: every() some() filter() map() forEach()

  • 归并:reduce()

eg: arr List.forEach(item => {
item. product = Arr_PRODUCT_LIST.filter(product => +product. price == item. amount /item. quantity ). pop () || {};
item. statusItem = this . statusColorBox [item.status]
console . log (item);
})