![](/img/trans.png)
[英]Can anyone explain the difference between those two codes? And why does the second one work and the first doesn't?
[英]Can anyone explain me the difference between these two loopings?
http://jsperf.com/jquery-each-vs-for-loop/108
for (var b = a[0], len = a.length; len; b = a[--len]) {
newArray.push(
b
);
}
和
for (var i = 0, len = a.length; i < len; i++) {
newArray.push(
a[i]
);
}
你的第一個例子做了一些非常不同的事情 看看這個:
var a = [1,2,3,4],
newArray = [];
for (var b = a[0], len = a.length; len; b = a[--len]) {
newArray.push(b);
}
> newArray
[1, 4, 3, 2]
你的第二個例子產生了預期的[1, 2, 3, 4]
。
如果您需要了解算法,將for
-notation轉換for
while循環並擴展遞減和遞增運算符可能會更容易:
/* first example */
var b = a[0],
len = a.length;
while (len) {
newArray.push(b);
len = len-1;
b = a[len];
}
/* second example */
var i = 0,
len = a.length;
while (i < len) {
newArray.push( a[i] );
i = i+1;
}
我認為第一個循環的主要好處是a
被緩存在len
,然后用作單個布爾值:通過簡化循環條件可以獲得一點時間。 然而! 它不會產生與輸出相同的數組。
假設你有一個元素:[0,1,2,3,4,5,6,7,8,9] - 循環首先處理[0],然后處理[ - len],在我們的例子中是[9]。 你的最終結果將是newArray = [0,9,8,7,6,5,4,3,2,1]。
因此,為什么它更快更重要,因為它做錯了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.