如何使用 JavaScript 遍历数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6208964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:46:09  来源:igfitidea点击:

How to loop over an Array with JavaScript?

javascriptjqueryarrays

提问by coffeemonitor

I have a string that has data separated by a pipe character (|).

我有一个字符串,其中的数据由管道字符 ( |)分隔。

Example

例子

var somestring = "data1|data2|data3";
var separated = somestring.split("|");

I know how to use the split()to separate each data.

我知道如何使用split()来分隔每个数据。

However, I don't know how many pipes there will be in the resulting Array.

但是,我不知道结果中会有多少管道Array

In jQuery or JavaScript, how do I loop over the array returned?

在 jQuery 或 JavaScript 中,如何遍历返回的数组?

回答by alex

In jQuery or JavaScript, how do I loop through each separated variable?

在 jQuery 或 JavaScript 中,如何遍历每个分隔的变量?

You basically just need to iterate over the resulting Array.

您基本上只需要迭代生成的Array.

jQuery

jQuery

$.eachloop

$.each环形

This method is easy to work with, and benefits in the variables used being encapsulated.

这种方法很容易使用,并且有利于封装使用的变量。

$.each(separated, function(index, chunk) {
    // `chunk` is each member of the array.
});

jsFiddle.

js小提琴

Of course, jQuery isJavaScript so any of the below methods will also work.

当然,jQueryJavaScript,所以下面的任何方法都可以使用。

JavaScript

JavaScript

forloop

for环形

This is the recommended way.

这是推荐的方式。

for (var i = 0, length = separated.length; i < length; i++) {
    var chunk = separated[i];
    // `chunk` is each member of the array.
}

jsFiddle.

js小提琴

You'll notice too the lengthproperty is cached so it is not looked up on each iteration. Some browsers already optimise for this, however IE appears to still benefit from it cached. It only takes 5 seconds to do, so you may as well keep IE users happy too.

您也会注意到该length属性已缓存,因此不会在每次迭代时查找。一些浏览器已经为此进行了优化,但是 IE 似乎仍然可以从缓存中受益。只需 5 秒钟即可完成,因此您也可以让 IE 用户满意。

You may want to define iand chunkoutside of the forloop, because JavaScript has no block scope (unless you're using let), and those variables will exist before (declaration hoisted) and after (no block scope).

您可能希望在循环之外定义i和,因为 JavaScript 没有块作用域(除非您使用),并且这些变量将存在于之前(声明提升)和之后(无块作用域)。chunkforlet

for ( in )loop

for ( in )环形

This loop is generally not recommended, as it should be used for iterating over object properties only, not array like member properties.

通常不推荐使用此循环,因为它应该仅用于迭代对象属性,而不是像成员属性那样的数组。

for (var chunk in separated) {
     if ( ! separated.hasOwnProperty(chunk)) {
         continue;
     }
     // `separated[chunk]` is each member of the array.   
}

jsFiddle.

js小提琴

This loop will loop over all properties up the prototype chain, so hasOwnProperty()must be used. For this reason it is not recommended for arrays.

这个循环将遍历原型链上的所有属性,因此hasOwnProperty()必须使用。因此,不建议将其用于阵列。

for ( of )loop

for ( of )环形

This loop is standardized in ECMA 6 and is able to loop over NodeLists and iterators.

这个循环在 ECMA 6 中被标准化并且能够循环遍历NodeLists 和迭代器。

for (var chunk of separated) {
     // `chunk` is each member of the array.   
}

jsFiddle

js小提琴

forEach()method

forEach()方法

This method is an addition to the ECMA-262 standard. It's not available in IE8, but it can be shimmedrelatively easily.

此方法是对 ECMA-262 标准的补充。它在 IE8 中不可用,但可以相对容易地填充

separated.forEach(function(chunk, index) {
     // `chunk` is each member of the array.   
});

jsFiddle.

js小提琴

Other specialised methods

其他专业方法

If you're looking to iterate for a specific goal, it may be useful to use a specialised iterator. Keep in mind these also don't have the best browser support.

如果您希望针对特定目标进行迭代,则使用专门的迭代器可能会很有用。请记住,这些也没有最好的浏览器支持。

filtermethod

filter方法

Creates a mew array of the elements which the associated callback returned truthyfor.

创建关联回调为其返回值的元素的 mew 数组。

separated.filter(function(element) {
    return +element > 255;
});

reducemethod

reduce方法

Creates a new value based on reducing the elements of the array, from left to right.

根据从左到右减少数组元素来创建新值。

separated.reduce(function(accumulator, element) {
    return accumulator.concat(element);
}, "");

See also the reduceRightmethod.

另见reduceRight方法。

mapmethod

map方法

Creates a new array, replacing each element with the returned value of the associated callback.

创建一个新数组,用关联回调的返回值替换每个元素。

separated.map(function(element) {
    return element.substr(0, 1);
});

everymethod

every方法

Returns a boolean value of which is the result of every element in the array passing the test. This method short circuits, i.e. it returns whenever one element's callback doesn't return truthy.

返回一个布尔值,它是数组中每个元素通过测试的结果。此方法短路,即只要一个元素的回调不返回truthy就返回。

separated.every(function(element) {
    return element.substr(0, 1) == "a";
});

somemethod

some方法

Returns a boolean value of which is the result of some element in the array passing the test. This method short circuits, i.e. it returns whenever one element's callback passes the test.

返回一个布尔值,它是数组中某个元素通过测试的结果。此方法短路,即只要一个元素的回调通过测试,它就会返回。

separated.some(function(element) {
    return element.substr(0, 1) == "a";
});

回答by Daniel A. White

separated.lengthshould be all you need.

separated.length应该是你所需要的。

回答by Rob Raisch

str.split() returns an array of values, so in your example, since 'separated' is an array, you could:

str.split() 返回一个值数组,因此在您的示例中,由于 'separated' 是一个数组,您可以:

for (var i=0, len=separated.length; i < len; i++) {
   // do something with separated[i]
}

回答by Billy Moon

you can do it in jquery like this

你可以像这样在jquery中做到这一点

$.each(separated,function(key,item){ alert('here is ' + item + ' at position ' + key) })

回答by Codecraft

Loop through with a FOR...NEXT construct like in most other languages:

像大多数其他语言一样,使用 FOR...NEXT 结构循环:

var somestring = "data1|data2|data3";
var separated = somestring.split("|");

for (i=0 ; i<separated.length; i++) {
 document.write(separated[i]);
 document.write("<br/>");
}

回答by Ivan

If your question really is "how do I loop through each separated variable?" then:

如果您的问题真的是“我如何遍历每个分离的变量?” 然后:

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

//or  (apparently this is deprecated)

for(var a in separated)
{
  //Do something with a
}