gpt4 book ai didi

JavaScript 数组 : is there a method that is a cross between splice and filter?

转载 作者:行者123 更新时间:2023-12-01 01:39:20 25 4
gpt4 key购买 nike

我有一个对象数组,并且想要:

  1. 从数组中删除某些对象
  2. 在第二步中处理移除的对象

我事先并不知道这些物体在哪里。为了识别它们,我需要使用一个函数来查询它们的属性。在第二个数组中检索已删除的对象是有意义的。

我曾希望找到一个像 filtersplice 这样的原生方法来做到这一点。以下是我提出的解决方案:

if (!Array.prototype.cherrypick) {
Array.prototype.cherrypick = function(fn) {
let basket = []
let ii = this.length
let item

for ( ; ii-- ; ) {
item = this[ii]

if (fn(item)) {
basket.unshift(item)
this.splice(ii, 1)
}
}

return basket
}
}

我是不是错过了什么?是否有本地方法可以做到这一点?我的解决方案在某种程度上不健全吗?

最佳答案

Have I missed something? Is there a native method that does this already?

不,大多数 native 实用程序方法都会尝试不改变数组,而是返回一个新数组。

Is my solution unsound in some way?

像您一样重复使用spliceunshift效率非常低。最好写一下

if (typeof Array.prototype.cherrypick == "function")
console.warn("something already defines Array#cherrypick!");
Array.prototype.cherrypick = function(predicate) {
let removed = [];
for (let i=0, j=0; i<this.length; i++) {
const item = this[i];
if (fn(item)) {
removed.push(item);
} else {
this[j++] = item; // keep in array, but at new position
}
}
this.length = j; // removes rest
return removed;
};

关于JavaScript 数组 : is there a method that is a cross between splice and filter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52558800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com