JavaScript 数组常用方法

252 阅读4分钟

JavaScript 数组常用方法

适用于 ES6+ 与 Vue/React 开发场景


一、变异方法(修改原数组)

这些方法会 直接修改原数组,并返回结果。Vue 能监听这些变化并触发更新。

方法说明示例
​push(...items)​在末尾添加元素,返回新长度​arr.push(4)​ → [1,2,3,4]​
​pop()​移除最后一个元素,返回被删值​arr.pop()​ → 3​,arr=[1,2]​
​unshift(...items)​在开头添加元素,返回新长度​arr.unshift(0)​ → [0,1,2,3]​
​shift()​移除第一个元素,返回被删值​arr.shift()​ → 1​,arr=[2,3]​
​splice(start, deleteCount, ...items)​从 start​ 删除 deleteCount​ 个,并插入新元素​arr.splice(1,1,'x')​ → [1,'x',3]​
​sort((a,b) => a-b)​排序数组(⚠️ 默认按字符串排序)​[3,1,10].sort((a,b)=>a-b)​ → [1,3,10]​
​reverse()​反转数组顺序​[1,2,3].reverse()​ → [3,2,1]​

✅ Vue 响应式:以上方法均能触发视图更新。


二、非变异方法(返回新数组)

不修改原数组,返回新数组。推荐用于函数式编程和 Vue/React 不可变数据(Immutable)模式。

方法说明示例
​concat(arr1, arr2)​合并数组​[1].concat([2],[3])​ → [1,2,3]​
​slice(start, end)​截取子数组 [start, end)​​[1,2,3].slice(1,3)​ → [2,3]​
​map(fn)​映射每个元素生成新数组​[1,2].map(x=>x*2)​ → [2,4]​
​filter(fn)​过滤符合条件的元素​[1,2,3].filter(x=>x>1)​ → [2,3]​
​join(separator)​将数组转为字符串​['a','b'].join('-')​ → "a-b"​
​flat(depth)​扁平化嵌套数组​[1,[2,3]].flat()​ → [1,2,3]​
​flatMap(fn)​先 map 再 flat 一层​[['a'],['b']].flatMap(x=>x)​ → ['a','b']​

✅ 推荐:配合赋值更新 Vue 响应式数据:list = list.filter(...)​。

三、遍历与查找方法

方法作用返回值
​forEach()​遍历执行函数​undefined​
​find()​找第一个符合条件的元素元素 orundefined​
​findIndex()​找第一个符合条件的索引索引 or-1​
​includes()​是否包含某值​true/false​
​indexOf()​查找元素首次出现索引索引 or-1​
​lastIndexOf()​查找最后一次出现索引索引 or-1​

✅ 示例

let users = [  { id: 1, name: 'Alice' },  { id: 2, name: 'Bob' },  { id: 3, name: 'Charlie' }];

// forEach: 遍历
users.forEach(u => console.log(u.name));

// find: 找 id 为 2 的用户
users.find(u => u.id === 2); // {id:2, name:'Bob'}

// findIndex: 找索引
users.findIndex(u => u.name === 'Bob'); // 1

// includes: 是否包含
[1,2,3].includes(2); // true

// indexOf: 第一次出现位置
['a','b','a'].indexOf('a'); // 0
['a','b','a'].lastIndexOf('a'); // 2

四、聚合与判断方法

方法作用返回值
​some()​是否有任一元素满足条件​true/false​
​every()​是否所有元素都满足条件​true/false​
​reduce()​累计计算(求和、扁平化等)累积值
​reduceRight()​从右往左 reduce累积值

✅ 示例

let nums = [1, 2, 3, 4];

// some: 是否有偶数
nums.some(x => x % 2 === 0); // true

// every: 是否都大于 0
nums.every(x => x > 0); // true

// reduce: 求和
nums.reduce((sum, n) => sum + n, 0); // 10

// reduce: 统计字符出现次数
'hello'.split('').reduce((acc, c) => {
  acc[c] = (acc[c] || 0) + 1;
  return acc;
}, {}); // { h:1, e:1, l:2, o:1 }

// reduceRight: 从右合并
['a','b','c'].reduceRight((acc, s) => acc + s, ''); // "cba"

五、其他实用方法

方法作用
​Array.from()​将类数组转为数组
​Array.of()​创建数组(替代new Array()​)
​Array.isArray()​判断是否为数组
​flat()​扁平化嵌套数组
​flatMap()​map 后 flat 一层
​fill()​填充固定值

✅ 示例

// Array.from: 转类数组(如 arguments, NodeList)
Array.from('abc'); // ['a','b','c']
Array.from({ length: 3 }, (_, i) => i); // [0,1,2]

// Array.of: 创建数组
Array.of(1);     // [1]
Array.of(1,2,3); // [1,2,3]

// Array.isArray: 安全判断数组
Array.isArray([]); // true

// flat: 扁平化
[1, [2, 3], [4, [5]]].flat();   // [1,2,3,4,[5]]
[1, [2, 3], [4, [5]]].flat(2);  // [1,2,3,4,5]

// fill: 填充
[0,0,0].fill(7); // [7,7,7]
['a','b','c'].fill('x', 1, 3); // ['a','x','x']

// keys(), values(), entries()
for (let [i, v] of ['a','b'].entries()) {
  console.log(i, v); // 0 a, 1 b
}

六、Vue 3 中的响应式建议

在 Vue 3 中:

  • ✅ 变异方法(push​, pop​, splice​, unshift​, shift​)会被监听,能触发视图更新
  • ✅ 函数式方法(map​, filter​, slice​, 扩展运算符)应配合赋值使用:
// ✅ 正确:赋值新数组
list.value = list.value.filter(item => item.id !== 1)

// ✅ 或使用扩展运算符
list.value = [...list.value, newItem]
list.value = [newItem, ...list.value] // 开头插入

七、常用场景速查表

场景推荐方法
添加元素到末尾​push()​或[...arr, x]​
添加元素到开头​unshift()​或[x, ...arr]​
删除某个元素(按值)​filter()​(推荐)或findIndex + splice​
修改某一项​map()​或splice(index, 1, newItem)​
查找元素​find()​
查找索引​findIndex()​
数组合并​[...arr1, ...arr2]​或concat()​
数组去重​[...new Set(arr)]​
数组求和​reduce()​
数组扁平化​flat()​或flatMap()​

✅ 总结

类型方法举例是否修改原数组
变异方法​push​,pop​,splice​,sort​✅ 是
非变异方法​map​,filter​,slice​,concat​❌ 否(返回新数组)
查找​find​,findIndex​,includes​
聚合​some​,every​,reduce​

💡 最佳实践:

  • 多用函数式方法(map​, filter​, reduce​)提高可维护性
  • 在 Vue 中优先使用不可变数据(赋值新数组)
  • 性能敏感时可使用 splice​ 等原地操作