如何使用JavaScript对数组进行循环?

时间:2022-06-17 22:56:04

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.

但是,我不知道结果数组中有多少管道。

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

在jQuery或JavaScript中,如何循环返回数组?

7 个解决方案

#1


35  

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

在jQuery或JavaScript中,如何循环每个单独的变量?

You basically just need to iterate over the resulting Array.

基本上只需要遍历结果数组。

jQuery

$.each loop

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.

jsFiddle。

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

当然,jQuery是JavaScript的,因此下面的任何方法都可以工作。

JavaScript

for loop

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.

jsFiddle。

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.

您将注意到长度属性被缓存,因此它不会在每次迭代中被查询。一些浏览器已经为此进行了优化,但是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).

您可能想要在for循环之外定义i和chunk,因为JavaScript没有块范围(除非使用let),并且这些变量将在(声明提升)之前和之后(没有块范围)存在。

for ( in ) loop

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.

jsFiddle。

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

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

这个循环在ECMA 6中是标准化的,能够在节点列表和迭代器上进行循环。

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

jsFiddle

jsFiddle

forEach() method

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

这种方法是对ECMA-262标准的补充。它在IE8中是不可用的,但是它可以相对容易地进行摆振。

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

jsFiddle.

jsFiddle。

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

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

创建关联回调返回truthy的元素的mew数组。

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

reduce method

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

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

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.

返回一个布尔值,该值是通过测试的数组中的每个元素的结果。该方法短路,即当一个元素的回调不返回真值时返回。

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

some method

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";
});

#2


1  

separated.length should be all you need.

分离。长度应该是你所需要的。

#3


1  

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]
}

#4


0  

you can do it in jquery like this

你可以用jquery这样做

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

#5


0  

If you mean you want to know the length of the resulting array, what about separated.length?

如果你想知道结果数组的长度,那么分色。长度呢?

basic loop through arrays:

基本循环数组:

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

for utmost speed (especially in IE, see comments) cache the arrays length:

对于最大速度(特别是在IE中,请参阅注释),缓存数组长度:

var i = 0,                  //now you can omit var i=0 in the loop
    len = separated.length; //arrays length is cached

for (; i<len; i++){
  // do something with separated[i]
}

#6


-1  

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
}

#7


-1  

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

循环使用FOR…下一个构造与大多数其他语言相似:

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

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

#1


35  

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

在jQuery或JavaScript中,如何循环每个单独的变量?

You basically just need to iterate over the resulting Array.

基本上只需要遍历结果数组。

jQuery

$.each loop

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.

jsFiddle。

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

当然,jQuery是JavaScript的,因此下面的任何方法都可以工作。

JavaScript

for loop

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.

jsFiddle。

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.

您将注意到长度属性被缓存,因此它不会在每次迭代中被查询。一些浏览器已经为此进行了优化,但是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).

您可能想要在for循环之外定义i和chunk,因为JavaScript没有块范围(除非使用let),并且这些变量将在(声明提升)之前和之后(没有块范围)存在。

for ( in ) loop

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.

jsFiddle。

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

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

这个循环在ECMA 6中是标准化的,能够在节点列表和迭代器上进行循环。

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

jsFiddle

jsFiddle

forEach() method

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

这种方法是对ECMA-262标准的补充。它在IE8中是不可用的,但是它可以相对容易地进行摆振。

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

jsFiddle.

jsFiddle。

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

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

创建关联回调返回truthy的元素的mew数组。

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

reduce method

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

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

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.

返回一个布尔值,该值是通过测试的数组中的每个元素的结果。该方法短路,即当一个元素的回调不返回真值时返回。

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

some method

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";
});

#2


1  

separated.length should be all you need.

分离。长度应该是你所需要的。

#3


1  

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]
}

#4


0  

you can do it in jquery like this

你可以用jquery这样做

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

#5


0  

If you mean you want to know the length of the resulting array, what about separated.length?

如果你想知道结果数组的长度,那么分色。长度呢?

basic loop through arrays:

基本循环数组:

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

for utmost speed (especially in IE, see comments) cache the arrays length:

对于最大速度(特别是在IE中,请参阅注释),缓存数组长度:

var i = 0,                  //now you can omit var i=0 in the loop
    len = separated.length; //arrays length is cached

for (; i<len; i++){
  // do something with separated[i]
}

#6


-1  

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
}

#7


-1  

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

循环使用FOR…下一个构造与大多数其他语言相似:

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

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