我在 JS 中实现了这样的 each
函数:
Object.prototype.each = function(fn){
for (var x in this){
if (this.hasOwnProperty(x)){
fn(x);
}
}
return this;
};
var o = {'a' : 'apple', 'b' : 'bat', 'c' : 'cat'};
o.each(function(i){
alert(i);
});
虽然这很好用。有什么不妥吗。因为我在学JS所以问。
还有为什么我这样做会产生错误:
{'a' : 'apple', 'b' : 'bat', 'c' : 'cat'}.each(function(i){
alert(i);
});
最佳答案
您需要在对象周围加上括号,否则由于左右花括号,它会将其解释为一个 block 。
({'a' : 'apple', 'b' : 'bat', 'c' : 'cat'}).each(function(i){
alert(i);
});
当你不带括号时,解释器将“看到”这个:
{ // open block statement
'a' : 'apple', 'b' : 'bat', 'c' : 'cat' // not a valid expression!
}.each(function(i){ // there's no dot property access notation for statements!
alert(i);
});
这是一个只有一个表达式的 block 。但是,由于这不是有效的表达式,它将返回语法错误。即使它是一个有效的表达式,它仍然会给你一个错误,因为 block 没有属性,因此点属性访问符号不适用:
{ console.log("hello world"); }.each(function(){})
因此,您需要通过将对象括在括号中来告诉解释器该对象是一个表达式以消除歧义(因为您不能将语句放在括号内 - 只能是表达式)。
关于javascript - 在类似于 jQuery 的 vanilla JS 中实现每个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9069408/