Javascript 如何使jquery每个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3647533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make jquery each a number
提问by zjm1126
This is my code:
这是我的代码:
$.each(3, function(n) {
alert(n);
});
I want to alert three times but it doesn't work. What can I do?
我想提醒三遍,但它不起作用。我能做什么?
回答by kennytm
eachmust operate on an object. Try to create an array of length 3, e.g.
each必须对一个对象进行操作。尝试创建一个长度为 3 的数组,例如
$.each(new Array(3),
function(n){alert(n);}
);
Of course, I don't see the reason to avoid normal Javascript.
当然,我看不出避免使用普通 Javascript 的原因。
for (var n = 0; n < 3; ++ n)
alert(n);
回答by user113716
Late answer, but another option would be to prototype the Number with a method that would call a callback that many times.
迟到的答案,但另一种选择是使用可以多次调用回调的方法对 Number 进行原型设计。
Number.prototype.loop = function(cb) {
for (var i = 0; i < this; i++) {
cb.call(this, i);
}
return this + 0;
};
Then call it like this:
然后像这样调用它:
(3).loop(i => alert(i))
However, it should be noted it is considered bad practice to modify standard prototypes like this. See the section on this MDN page called Bad practice: Extension of native prototypes.
但是,应该注意的是,像这样修改标准原型被认为是不好的做法。请参阅此 MDN 页面上名为Bad practice: Extension of native prototypes 的部分。
RightJS does something like this. (Others probably too.)
RightJS 做这样的事情。(其他人可能也是。)
回答by SLaks
You can't.$.eachcan only iterate over arrays or objects.
You're looking for the forloop:
你不能。$.each只能迭代数组或对象。你正在寻找for循环:
for(var n = 0; n < 5; n++) {
alert(n);
}

