标签云

微信群

扫码加入我们

WeChat QR Code

In Java you can use a for loop to traverse objects in an array as follows:String[] myStringArray = {"Hello", "World"};for (String s : myStringArray){// Do something}Can you do the same in JavaScript?


Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects?And use a sequential one for filling one? Is this correct?

2019年08月19日11分53秒

no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...

2019年08月19日11分53秒

related - stackoverflow.com/questions/5349425/…

2019年08月19日11分53秒

related - stackoverflow.com/q/6208964/31671

2019年08月19日11分53秒

jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays

2019年08月19日11分53秒

This is the reason ( by CMS him self )stackoverflow.com/questions/1885317/…

2019年08月19日11分53秒

DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

2019年08月19日11分53秒

StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

2019年08月19日11分53秒

jsperf.com/caching-array-length/4Here is a test to see if it is worth caching the length of an array in a Javascript loop

2019年08月19日11分53秒

Why is this preferable to someArray.forEach(function(item){}), that it should have so many upvotes?

2019年08月19日11分53秒

Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference.

2019年08月19日11分53秒

mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

2019年08月19日11分53秒

DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); }outputs 0, 1, 3, and 4.a.length is still 5.

2019年08月19日11分53秒

GrijeshChauhan - correct.For instance, IE through version 8 doesn't support it. See this question.

2019年08月19日11分53秒

JoãoPimentelFerreira there was some discussion of that in earlier comments, but I decided to rework the answer to incorporate it there as well; the differences in the way the three solutions handle sparse arrays is worth calling out. Thanks for the nudge.

2019年08月19日11分53秒

No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

2019年08月19日11分53秒

That particular example is probably better implemented using Array.forEach. map is for generating a new array.

2019年08月19日11分53秒

hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard, is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I think the Array.prototype.forEach method is more semantically correct... also please don't suggest the for-in statement, see my answer for more details :)

2019年08月19日11分53秒

The difference between forEach and map is that the former doesn't return the results of the iteration.map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name.It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on.Whereas forEach just does something with each element, semantics unspecified.

2019年08月19日11分53秒

Downvote because if you're not actually mapping something, then using [].map is misleading. [].forEach makes semantic sense and also passes the same three arguments to the function.

2019年08月19日11分53秒

myArray.forEach(function(obj) {}); is still the best

2019年08月19日11分53秒

a tiny improvement: you could use ++i instead of i++

2019年08月19日11分53秒

++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

2019年08月19日11分53秒

You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

2019年08月19日11分53秒

Rui Marques -- you can name your variable i_stop or i_end instead of len.It's just as readable (if not more so!), and you will naturally avoid this kind of problem (since your other loop will get, e.g., j_stop).

2019年08月19日11分53秒

If you're using ES6, I would suggest const s instead of var s

2019年08月20日11分53秒

See also caniuse.com/es6

2019年08月19日11分53秒

In my tests on large arrays, using var s of arr is almost double (1.9x) the execution time compared to using a simple counter for-loop and retrieving elements by index in nodejs

2019年08月19日11分53秒

Addition: IE supports forEach since version 9, see forEach Method MSDN

2019年08月19日11分53秒

The first example of the "while" syntax won't work if any of the array elements is falsy.

2019年08月19日11分53秒

... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away the need to declare the index and item variables beforehand...

2019年08月19日11分53秒

StijndeWitt But for this applies: if the value is falsy, it won't work...

2019年08月19日11分53秒

While iterating over collection, you should care about optimization. As it may effect page performance.

2019年08月19日11分53秒

For the people that don't get what is so ingenious: The i-- expression is first evaluated and allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.

2019年08月19日11分53秒

falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)

2019年08月19日11分53秒

I've seen the term falsish being used by people I consider gurus. If it's good enough for them it's good enough for me. Also a but disappointed to see that my comment that is actually ontopic and adds explanation/insight gets 0 upvotes, but the comment that nitpicks on a term in my comment gets 4. Ah well just a matter of priorities I guess.

1970年01月01日00分03秒

"Caching the length"?The length is stored as an integer in the array, it's not measured every time you access it.There's no benefit here in copying the value of length into another variable.

2019年08月19日11分53秒

Mouscellaneous These days there certainly is not; in years past iterating JavaScript arrays caching the length on the JavaScript side (instead of reaching across the implementation) was a clear perf gain (when microoptimizing). For example, for (var i=0,len=array.length;i<len;++i) was a common, sensible loop to write.

2019年08月19日11分53秒

Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code is called enough times and it detects that the length is not modified by the loop.

2019年08月19日11分53秒

Thanks for the info Phrogz it's true that there is a lot of optimizations that the VM can make, but since older browsers don't have this it would still be best practice to optimize for it since it is so cheap.

2019年08月19日11分53秒

Gabriel: Why? Please give real-world examples showing that not caching the length is actually a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I will fix that one loop that actually poses a problem once I encounter it...

2019年08月19日11分53秒

StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead relying on underscore for things like _.each, _.map etc. to do these things. When I did write loops like this I cached the length primarily so that all my variable declaration were in one place, at the top of my function. Following my advice in this regard is inconsequential to any real world application. Premature optimization is super bad, but if optimization happens to result from stylistic decisions I don't think it actually matters.

2019年08月19日11分53秒

Gabriel I believe JavaScript already supports the map function on arrays, no need to introduce an additional lib for that.

2019年08月19日11分53秒

It's a shame the ES5 forEach isn't at the top of the answers because it most closely matches what the OP was asking for.

2019年08月19日11分53秒

For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of Underscore's that improves upon it in many ways.

2019年08月19日11分53秒

Why use underscore if ECMA-262 has been added the forEach methor. The native code is always better.

2019年08月19日11分53秒

Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

2019年08月19日11分53秒

is better use i = i +1 instead of i++

2019年08月19日11分53秒

Could be improved: Please use: ++i instead of i++, this will avoid an temporary object. So it reduces memory usage and cpu time (no allocation required)!

2019年08月19日11分53秒

PowerStat can you provide a link or reference about that ? I've never aheard about it, sounds interesting...

2019年08月19日11分53秒

colxi For such interesting things you should read the hardcore C++ stuff from Herb Sutter and Scott Meyers. The ++i vs i++ thing is from the book: Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions - I thing you could also find it on gotw.ca but can be proved for every programing language.

2019年08月20日11分53秒

jQuery for everything?

2019年08月19日11分53秒

Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice against this except in code that is already heavily using jQuery anyway.

2019年08月19日11分53秒

Update: These days, you can use Array.forEach to get much of the same effect with native arrays.

2019年08月19日11分53秒

Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

2019年08月19日11分53秒

The loop condition could be (item=someArray[i]) !== undefined.

2019年08月19日11分53秒

And how about using for (var i in array) if (++i) ?

2019年08月19日11分53秒

for...in should be avoided for Array-like objects

2019年08月19日11分53秒

This loop doesn't seem to follow order of items in the array.

2019年08月19日11分53秒

My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

2019年08月19日11分53秒

bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

2019年08月19日11分53秒

breaks on falsey items.

2019年08月19日11分53秒

did you mean "x =" on the first line?

2019年08月19日11分53秒

You'd rather want to use .forEach() and drop the return e;

2019年08月19日11分53秒

as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

2019年08月19日11分53秒

It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

2019年08月19日11分53秒