7

我正在使用以下脚本来迭代对象(我不知道哪个最好用,请告诉我哪个最好):

var days = {Sunday: 0, Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6};

$.each(days, function(key, value){
    $('#days').append('<li>' + key + '(' + value + ')</li>');
});


for(var key in days){
    $('#days').append('<li>' + key + '(' + days[key] + ')</li>');
}
4

3 回答 3

4

无论哪种方式,您都应该缓存该选择器:

var elem = $( '#days' );
$.each(days,function(key,value){
    elem.append('<li>'+key+'('+value+')</li>');
});

.each() 在这种情况下会更好。图案更干净。

使用 for 循环,您需要使用 obj.hasOwnProperty(key) 以便您不会挖掘继承的属性......这增加了另一层缩进:

var elem = $( '#days' );
for( var key in days ){
  if( days.hasOwnProperty( key ) ){
    elem.append('<li>'+key+'('+days[key]+')</li>');
  }
}
于 2012-09-14T04:37:54.097 回答
2

It is clear without any performance tests that native javascript for loop is faster, but there is no big difference for small arrays like 10-20 small items. So use whichever you want.

于 2012-09-14T04:35:08.713 回答
0

Features of $.each: It will stop looping if the function returns false. It works for both objects and arrays. $(this) refers to the current element being processed.

Drawbacks of $.each: There's a little more overhead, as it does some initial checking of arguments and has to perform a function call for each element.

But as others said, the overhead is likely to be negligible unless you're processing a large number of items.

One other benefit of $.each() is simply the easy recognition of the word -- having it at the beginning of a statement makes it obvious that you're looping over a collection. It's also easy to search for.

于 2012-09-14T04:32:48.307 回答