使用 pullat 可以直接修改原数组并返回被移除元素,1. 需引入 lodash;2. 可一次移除多个指定索引元素,比 splice 更简洁;3. 若不想修改原数组,可用 slice 拷贝后再操作;4. filter 适合不修改原数组的场景;5. 性能受数组大小和移除元素数量影响,但通常可接受。

移除数组指定索引的值,用
pullAt
直接看怎么用吧。
// 假设你有这样一个数组 const myArray = ['a', 'b', 'c', 'd', 'e']; // 你想移除索引 1 和 3 的元素 (也就是 'b' 和 'd') const removedElements = _.pullAt(myArray, [1, 3]); console.log(myArray); // 输出: ['a', 'c', 'e'] - 原始数组已经被修改 console.log(removedElements); // 输出: ['b', 'd'] - 被移除的元素
看到了吗?
pullAt
其实移除数组元素的方法有很多,比如
splice
filter
splice
pullAt
const myArray = ['a', 'b', 'c', 'd', 'e']; const removed = myArray.splice(1, 1); // 从索引 1 开始,移除 1 个元素 console.log(myArray); // 输出: ['a', 'c', 'd', 'e'] console.log(removed); // 输出: ['b']
如果用
splice
filter
const myArray = ['a', 'b', 'c', 'd', 'e']; const indicesToRemove = [1, 3]; const newArray = myArray.filter((element, index) => !indicesToRemove.includes(index)); console.log(newArray); // 输出: ['a', 'c', 'e'] console.log(myArray); // 输出: ['a', 'b', 'c', 'd', 'e'] - 原始数组未被修改
filter
所以,如果需要修改原数组,并且一次移除多个指定索引的元素,
pullAt
filter
不想修改原数组? 简单! 先拷贝一份再操作。
const myArray = ['a', 'b', 'c', 'd', 'e']; // 使用 slice 创建数组的浅拷贝 const myArrayCopy = myArray.slice(); const removedElements = _.pullAt(myArrayCopy, [1, 3]); console.log(myArrayCopy); // 输出: ['a', 'c', 'e'] - 拷贝后的数组被修改 console.log(myArray); // 输出: ['a', 'b', 'c', 'd', 'e'] - 原始数组未被修改
slice()
pullAt
JSON.parse(JSON.stringify(myArray))
_.cloneDeep(myArray)
pullAt
pullAt
但是,现代 JavaScript 引擎对数组操作进行了优化,
pullAt
总而言之,
pullAt
以上就是js 怎样用pullAt移除数组指定索引的值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号