标签:
这里有。。http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript
var modules = [‘aaa‘,‘bbb‘]; for(var i in modules){ if (modules.hasOwnProperty(i)){ // do something here } }
Array.prototype.foo = "foo!"; var array = [‘a‘, ‘b‘, ‘c‘]; for (var i in array) { alert(array[i]); }
To directly answer the question: usually not. JavaScript only has that capability if you‘re lucky enough to be in control of the JavaScript interpreter being used (usually not the case if it‘s browser-side code), and that implementation includes the for...of feature from the proposed sixth version of the ECMAScript specification (code-named "Harmony"). If the stars have so aligned in your case, you can do this:
// ONLY WORKS IN ECMASCRIPT 6 "HARMONY" var s, myStringArray = ["Hello", "World"]; for (s of myStringArray) { // ... do something with s ... }
Or better yet, since Harmony also provides block-scoped variables via let:
// ONLY WORKS IN ECMASCRIPT 6 "HARMONY" var myStringArray = ["Hello", "World"]; for (let s of myStringArray) { // ... do something with s ... } // s is no longer defined here
似乎取不了下标。
Most JavaScript programmers are working in an environment that‘s not there yet, however. If you can assume the interpreter is compliant with version 5 of the specification (which means, for browser code, no versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called for each item in the list:
var myStringArray = [ "Hello", "World" ]; myStringArray.forEach( function(s,i) { // ... do something with s ... } );
这个也不错,和underscore一样简洁。
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length; for (i=0; i<len; ++i) { if (i in myStringArray) { s = myStringArray[i]; // ... do something with s ... } }
传统的方式
Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%. You will often see the length caching done in the loop initialization clause, like this:
var i, len, myStringArray = [ "Hello", "World" ]; for (len = myStringArray.length, i=0; i<len; ++i) {
The for...in syntax mentioned by others is for looping over an object‘s properties; since an Array in JavaScript is just an object with numeric property names (and a magical "length" property), you can theoretically loop over an Array with it. But the problem is that it doesn‘t restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for...insyntax should not be used for looping through Arrays.
_([‘aaa‘,‘bbb‘]).each(function(s,i){ console.log(s,i); } )
还是这个库用起来顺手。。
标签:
原文地址:http://my.oschina.net/uniquejava/blog/505435