問題描述
我偶然發現了幾種JavaScript循環的方法,我最喜歡的是:
for(var i = 0; i < a.length; i++){變量元素 = a[i];}
但正如這里測試的那樣 (http://www.robertnyman.com/2008/04/11/javascript-loop-performance/),它可能應該被寫成只計算一次長度.
在 jQuery 中有一個 .each 可以粘貼一個函數.我更喜歡這個,因為我不必像上面的解決方案那樣輸入兩次數組.
如果 JavaScript 支持宏,那么你自己動手做就是小菜一碟,但遺憾的是它不支持.
那你們用什么?
我已經開始在相關的地方使用迭代器.性能是合理的,但更重要的是它允許您封裝循環邏輯:
函數 createIterator(x) {變量 i = 0;返回函數(){返回 x[i++];};}
然后使用:
var iterator=createIterator(['a','b','c','d','e','f','g']);迭代器();
返回a";
迭代器();
返回b";
等等.
迭代整個列表并顯示每個項目:
<上一頁>無功電流;而(當前=迭代器()){控制臺.log(當前);}請注意,上述內容僅適用于迭代包含非虛假"值的列表.如果此數組包含以下任何一項:
- 0
- 錯誤
- "
- 空
- NaN
上一個循環會停在那個項目上,并不總是你想要/期望的.
為了避免這種用法:
var 當前;而((當前=迭代器())!==未定義){控制臺.log(當前);}
I have stumbled into several methods of looping in JavaScript, what I like the most is:
for(var i = 0; i < a.length; i++){
var element = a[i];
}
But as tested here (http://www.robertnyman.com/2008/04/11/javascript-loop-performance/), it should probably be written so that the length is only calculated once.
In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution.
If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not.
So what do you guys use?
I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:
function createIterator(x) {
var i = 0;
return function(){
return x[i++];
};
}
Then to use:
var iterator=createIterator(['a','b','c','d','e','f','g']);
iterator();
returns "a";
iterator();
returns "b";
and so on.
To iterate the whole list and display each item:
var current; while(current=iterator()) { console.log(current); }
Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:
- 0
- false
- ""
- null
- NaN
the previous loop would stop at that item, not always what you want/expect.
To avoid this use:
var current;
while((current=iterator())!==undefined)
{
console.log(current);
}
這篇關于在 JavaScript 中執行循環的最佳方法是什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!