JavaScript:对象的 filter()
ECMAScript 5 具有 Array
类型的 filter()
原型,但没有 Object
类型,如果我理解正确的话.
ECMAScript 5 has the filter()
prototype for Array
types, but not Object
types, if I understand correctly.
如何在 JavaScript 中为 Object
实现 filter()
?
How would I implement a filter()
for Object
s in JavaScript?
假设我有这个对象:
var foo = {
bar: "Yes"
};
我想写一个 filter()
可以在 Object
s 上工作:
And I want to write a filter()
that works on Object
s:
Object.prototype.filter = function(predicate) {
var result = {};
for (key in this) {
if (this.hasOwnProperty(key) && !predicate(this[key])) {
result[key] = this[key];
}
}
return result;
};
当我在以下演示中使用它时,它可以工作,但是当我将它添加到使用 jQuery 1.5 和 jQuery UI 1.8.9 的网站时,我在 FireBug 中遇到 JavaScript 错误.
This works when I use it in the following demo, but when I add it to my site that uses jQuery 1.5 and jQuery UI 1.8.9, I get JavaScript errors in FireBug.
Object.prototype.filter = function(predicate) {
var result = {};
for (key in this) {
if (this.hasOwnProperty(key) && !predicate(this[key])) {
console.log("copying");
result[key] = this[key];
}
}
return result;
};
var foo = {
bar: "Yes",
moo: undefined
};
foo = foo.filter(function(property) {
return typeof property === "undefined";
});
document.getElementById('disp').innerHTML = JSON.stringify(foo, undefined, ' ');
console.log(foo);
#disp {
white-space: pre;
font-family: monospace
}
<div id="disp"></div>
推荐答案
永远不要扩展 Object.prototype
.
你的代码会发生可怕的事情.事情会破裂.您正在扩展 所有 对象类型,包括对象字面量.
Horrible things will happen to your code. Things will break. You're extending all object types, including object literals.
这是一个您可以尝试的简单示例:
Here's a quick example you can try:
// Extend Object.prototype
Object.prototype.extended = "I'm everywhere!";
// See the result
alert( {}.extended ); // "I'm everywhere!"
alert( [].extended ); // "I'm everywhere!"
alert( new Date().extended ); // "I'm everywhere!"
alert( 3..extended ); // "I'm everywhere!"
alert( true.extended ); // "I'm everywhere!"
alert( "here?".extended ); // "I'm everywhere!"
<小时>
而是创建一个传递对象的函数.
Instead create a function that you pass the object.
Object.filter = function( obj, predicate) {
let result = {}, key;
for (key in obj) {
if (obj.hasOwnProperty(key) && !predicate(obj[key])) {
result[key] = obj[key];
}
}
return result;
};
相关文章