如何使用 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
How to loop over an Array with JavaScript?
提问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
$.each
loop
$.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.
});
Of course, jQuery isJavaScript so any of the below methods will also work.
当然,jQuery是JavaScript,所以下面的任何方法都可以使用。
JavaScript
JavaScript
for
loop
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.
}
You'll notice too the length
property 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 i
and chunk
outside of the for
loop, 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 没有块作用域(除非您使用),并且这些变量将存在于之前(声明提升)和之后(无块作用域)。chunk
for
let
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.
}
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 NodeList
s and iterators.
这个循环在 ECMA 6 中被标准化并且能够循环遍历NodeList
s 和迭代器。
for (var chunk of separated) {
// `chunk` is each member of the array.
}
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.
});
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.
如果您希望针对特定目标进行迭代,则使用专门的迭代器可能会很有用。请记住,这些也没有最好的浏览器支持。
filter
method
filter
方法
Creates a mew array of the elements which the associated callback returned truthyfor.
创建关联回调为其返回真值的元素的 mew 数组。
separated.filter(function(element) {
return +element > 255;
});
reduce
method
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 reduceRight
method.
另见reduceRight
方法。
map
method
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);
});
every
method
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";
});
some
method
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.length
should 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
}