Loop through an array in JavaScript

2018-12-30 22:49发布

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?

30条回答
裙下三千臣
2楼-- · 2018-12-30 23:24

There are various way to loop through array in JavaScript.

Generic loop:

var i;
for (i = 0; i < substr.length; ++i) {
    // Do something with `substr[i]`
}

ES5's forEach:

substr.forEach(function(item) {
    // Do something with `item`
});

jQuery.each:

jQuery.each(substr, function(index, item) {
    // Do something with `item` (or `this` is also `item` if you like)
});

Have a look this for detailed information or you can also check MDN for looping through an array in JavaScript & using jQuery check jQuery for each.

查看更多
倾城一夜雪
3楼-- · 2018-12-30 23:24

If anybody is interested in the performance side of the multiple mechanisms available for Array iterations , i've prepared the following JSPerf tests:

https://jsperf.com/fastest-array-iterator

Performamce results

Results :

The traditional for() iterator, is by far the fastest method, specially when used with the array length cached.

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // do something
}

The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead

查看更多
余生请多指教
4楼-- · 2018-12-30 23:27

Intro

Since my time in college, I've programmed in Java, JavaScript, Pascal, ABAP, PHP, Progress 4GL, C/C++ and possibly a few other languages I can't think of right now.

While they all have their own linguistic idiosyncrasies, each of these languages share many of the same basic concepts. Such concepts include procedures / functions, IF-statements, FOR-loops, and WHILE-loops.


A traditional for-loop

A traditional for loop has three components:

  1. The initialization: executed before the look block is executed the first time
  2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false
  3. The afterthought: performed every time after the loop block is executed

These three components are separated from each other by a ; symbol. Content for each of these three components is optional, which means that the following is the most minimal for loop possible:

for (;;) {
    // Do stuff
}

Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.

Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index:

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

Using a traditional for loop to loop through an array

The traditional way to loop through an array, is this:

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

Or, if you prefer to loop backwards, you do this:

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

There are, however, many variations possible, like for example this one:

for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

... or this one ...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... or this one:

var key = 0, value;
for (; value = myArray[key++];){
    console.log(value);
}

Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.

Note that each of these variations is supported by all browsers, including very very old ones!


A while loop

One alternative to a for loop is a while loop. To loop through an array, you could do this:

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}

Like traditional for loops, while loops are supported by even the oldest of browsers.

Also, note that every while loop can be rewritten as a for loop. For example, the while loop hereabove behaves the exact same way as this for-loop:

for(var key = 0; value = myArray[key++];){
    console.log(value);
}

For...in and for...of

In JavaScript, you can also do this:

for (i in myArray) {
    console.log(myArray[i]);
}

This should be used with care, however, as it doesn't behave the same as a traditional for loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.

As an alternative to for...in, there's now also for for...of. The following example shows the difference between a for...of loop and a for...in loop:

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7
}

Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.


Array.prototype.forEach()

An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});

Array.prototype.forEach() is supported by all modern browsers, as well as Internet Explorer 9 and later.


Libraries

Finally, many utility libraries also have their own foreach variation. AFAIK, the three most popular ones are these:

jQuery.each(), in jQuery:

$.each(myArray, function(key, value) {
    console.log(value);
});

_.each(), in Underscore.js:

_.each(myArray, function(value, key, myArray) {
    console.log(value);
});

_.forEach(), in Lodash.js:

_.forEach(myArray, function(value, key) {
    console.log(value);
});
查看更多
春风洒进眼中
5楼-- · 2018-12-30 23:27

Some use cases of looping through an array in the functional programming way in JavaScript:

1. Just loop through an array

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.

2. Check if any of the elements in an array pass a test

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. Transform to a new array

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.

4. Sum up a particular property, and calculate its average

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. Create a new array based on the original but without modifying it

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. Retrieve a subset of an array based on particular criteria

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

8. Sort an array

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

enter image description here

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

enter image description here

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.

References

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-30 23:27

The best way in my opinion is to use the Array.forEach function. If you cannot use that I would suggest to get the polyfill from MDN to make i available, it is certainly the safest way to iterate over an array in JavaScript.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

So as others has suggested, this is almost always what you want:

var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
numbers.forEach(function(n){
  sum += n;
});

This ensures that anything you need in the scope of processing the array stays within that scope, and that you are only processing the values of the array, not the object properties and other members, which is what for .. in does.

using a regular c style for loop works in most cases, it is just important to remember that everything within the loop shares it's scope with the rest of your program, the { } does not create a new scope.

Hence:

var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];

for(var i = 0; i<numbers.length; ++i){ 
  sum += numbers[i];
}

alert(i);

will output "11" - which may or may not be what you want.

Working jsFiddle example: https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/

查看更多
浮光初槿花落
7楼-- · 2018-12-30 23:28

Yes, you can do the same in JavaScript using loop, but not limited to that, many ways to do loop over arrays in JavaScrip, imagine you have this array below and you'd like to do a loop over it:

var arr = [1, 2, 3, 4, 5];

These are the solutions:

1) For loop

For loop is a common way looping through arrays in JavaScript, but no considered as the fastest solutions for large arrays:

for (var i=0, l=arr.length; i<l; i++) { 
  console.log(arr[i]);
}

2) While loop

While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:

let i=0;

while (arr.length>i) {
    console.log(arr[i]);
    i++;
}

3) Do while
Do while doing the same thing as while with some syntax difference as below:

let i=0;
do {
  console.log(arr[i]);
  i++;
}
while (arr.length>i);

These are the main ways to do javascript loops, but there are few more ways to do that.

Also we use for in loop for looping over objects in javascript.

Also look at map(), filter(), reduce() etc functions on Array in JavaScript. They may do things much faster and better than using while and for.

This is good article if you like to learn more about the async functions over arrays in JavaScript.

Functional programming has been making quite a splash in the development world these days. And for good reason: Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test.

One of the cornerstones of functional programming is its special use of lists and list operations. And those things are exactly what the sound like they are: arrays of things, and the stuff you do to them. But the functional mindset treats them a bit differently than you might expect.

This article will take a close look at what I like to call the "big three" list operations: map, filter, and reduce. Wrapping your head around these three functions is an important step towards being able to write clean functional code, and opens the doors to the vastly powerful techniques of functional and reactive programming.

It also means you'll never have to write a for loop again.

Read more>> here:

查看更多
登录 后发表回答