作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个对象数组,并且想要:
我事先并不知道这些物体在哪里。为了识别它们,我需要使用一个函数来查询它们的属性。在第二个数组中检索已删除的对象是有意义的。
我曾希望找到一个像 filter
或 splice
这样的原生方法来做到这一点。以下是我提出的解决方案:
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?
像您一样重复使用splice
和unshift
效率非常低。最好写一下
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/
我是一名优秀的程序员,十分优秀!