[英]JQuery from $.each to for loop
I am very new to JQuery, from examples I have managed to create loop, I know it`s simple question but I need your help. 我对JQuery还是很陌生,从我设法创建循环的示例中,我知道它很简单,但是我需要您的帮助。 How can I convert $.each loop:
如何转换$ .each循环:
$.getJSON('db.json', function(data)
{
$.each(data, function(key, val)
{
if(typeof val === 'object')
{
checkObj(key, val, items);
}
});
}
to for loop? 为了循环? I have tried:
我努力了:
for (var i=0; i< data.length; i++)
{
if(typeof val === 'object')
{
checkObj(key, val, items);
}
}
but what to do with key and val? 但是如何处理key和val呢?
You're very close (for arrays). 你非常接近(对于数组)。 Just add:
只需添加:
var val;
at the top and then 在顶部,然后
val = data[i];
in the loop. 在循环。
var i, val;
for (i=0; i< data.length; i++)
{
val = data[i];
if(typeof val === 'object')
{
checkObj(i, val, items);
// ^----- `i`, not `key`, since you used `i` instead of `key` for the loop
}
}
But my question would be: Why do that? 但我的问题是:为什么这样做?
$.each
is very handy, not least because it provides this nice contained scope for the key
/ i
and val
variables. $.each
非常方便, $.each
是因为它为key
/ i
和val
变量提供了这个包含好的范围。 If you're worried about making a function call on each iteration, don't be . 如果您担心每次迭代都要进行函数调用, 请不要这样做 。
$.each
also has a dual-nature: When you're giving it an array, it loops through the array elements. $.each
也具有双重性质:当你给它一个数组时,它会遍历数组元素。 But when you give it an object, it loops through the enumerable properties of the object. 但是当你给它一个对象时,它会遍历对象的可枚举属性。 Both are quite handy.
两者都很方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.