【发布时间】:2011-04-26 00:03:47
【问题描述】:
我正在尝试遍历一个数组。我有以下代码:
var currnt_image_list= '21,32,234,223';
var substr = currnt_image_list.split(','); // array here
我正在尝试从数组中取出所有数据。有人能带领我走上正确的道路吗?
【问题讨论】:
标签: javascript jquery arrays loops iteration
我正在尝试遍历一个数组。我有以下代码:
var currnt_image_list= '21,32,234,223';
var substr = currnt_image_list.split(','); // array here
我正在尝试从数组中取出所有数据。有人能带领我走上正确的道路吗?
【问题讨论】:
标签: javascript jquery arrays loops iteration
(更新:我的 other answer here 更彻底地列出了非 jQuery 选项。但下面的第三个选项 jQuery.each 不在其中。)
四个选项:
var i;
for (i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
或在 ES2015+ 中:
for (let i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
优点:直截了当,不依赖 jQuery,易于理解,在循环体中保留 this 的含义没有问题,没有不必要的函数调用开销(例如,在理论上更快,虽然事实上你必须有这么多的元素,你很有可能会遇到其他问题;details)。
forEach:从 ECMAScript5 开始,数组上有一个 forEach 函数,这使得遍历数组变得容易:
substr.forEach(function(item) {
// do something with `item`
});
(注意:还有很多其他功能,不仅仅是forEach;详情请参阅the answer referenced above。)
优点:声明式,如果你有一个方便的迭代器,可以为迭代器使用预构建的函数,如果你的循环体很复杂,函数调用的范围有时很有用,不需要@987654336 @ 包含范围内的变量。
缺点:如果您在包含的代码中使用this,并且您想在您的forEach 回调中使用this,您必须要么 A) 将其粘贴在变量中所以你可以在函数中使用它,B)将它作为第二个参数传递给forEach,所以forEach在回调期间将它设置为this,或者C)使用ES2015+ 箭头函数 ,结束this。如果你不做这些事情之一,在回调中this 将是undefined(在严格模式下)或全局对象(window)在松散模式下。曾经有第二个缺点是 forEach 没有得到普遍支持,但是在 2018 年,您将遇到的唯一一个没有 forEach 的浏览器是 IE8(它不能是 适当地在那里填充)。
for-of:for (const s of substr) { // Or `let` if you want to modify it in the loop body
// do something with `s`
}
有关其工作原理的详细信息,请参阅此答案顶部链接的答案。
优点:简单、直接,为数组中的条目提供了一个包含范围的变量(或上文中的常量)。
缺点:任何版本的 IE 都不支持。
jQuery.each(substr, function(index, item) {
// do something with `item` (or `this` is also `item` if you like)
});
优点:与forEach 的所有优点相同,而且您知道它就在那里,因为您使用的是 jQuery。
缺点:如果您在包含的代码中使用this,则必须将其粘贴在变量中,以便您可以在函数中使用它,因为this 表示其中的其他内容函数。
您可以通过使用$.proxy 来避免this 的事情:
jQuery.each(substr, $.proxy(function(index, item) {
// do something with `item` (`this` is the same as it was outside)
}, this));
...或Function#bind:
jQuery.each(substr, function(index, item) {
// do something with `item` (`this` is the same as it was outside)
}.bind(this));
...或者在 ES2015(“ES6”)中,箭头函数:
jQuery.each(substr, (index, item) => {
// do something with `item` (`this` is the same as it was outside)
});
不要为此使用for..in(或者,如果您这样做,请使用适当的保护措施)。你会看到人们说 to(事实上,这里有一个简单的答案),但是 for..in 并没有像许多人认为的那样做(它做了一些更有用的事情!)。具体来说,for..in 循环遍历对象的可枚举属性名称(而不是数组的索引)。由于数组是对象,并且它们唯一的可枚举属性默认情况下是索引,所以它似乎主要在平淡无奇的部署中工作。但这并不是一个安全的假设,即您可以将其用于此目的。这是一个探索:http://jsbin.com/exohi/3
我应该软化上面的“不要”。如果您正在处理稀疏数组(例如,数组总共有 15 个元素,但由于某种原因它们的索引分布在 0 到 150,000 的范围内,因此 length 是 150,001),和 如果您使用像 hasOwnProperty 这样的适当保护措施并检查属性名称是否真的是数字(参见上面的链接),for..in 可以是避免大量不必要循环的完全合理的方法,因为只会枚举填充的索引。
【讨论】:
.each() 或for...in 循环数组通常是个坏主意。这就像使用 for 或 while 慢的年龄一样。使用for loop 在循环之前缓存length 属性甚至是一个好主意。 for (var i = 0, len = substr.length; i < len; ...
Function#bind。 :-) 好点,补充。
i++ 和++i 之间的唯一区别是该表达式的结果,在上面的示例中从未使用过。 for 循环的工作方式如下:1. 初始化,2. 测试(如果为 false,则终止),3. 正文,4. 更新,5. 返回步骤 2。更新表达式的结果不用于任何事情。
jQuery.each(array, callback)
数组迭代
jQuery.each(array, function(Integer index, Object value){});
对象迭代
jQuery.each(object, function(string propertyName, object propertyValue){});
示例:
var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) {
console.log(index, val)
});
var myObj = { firstName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
console.log(propName, propVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
for循环
for (initialExpression; condition; incrementExpression)
statement
例子
var substr = [1, 2, 3, 4];
//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
console.log("loop", substr[i])
}
//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
console.log("reverse", substr[i])
}
//step loop
for(var i = 0; i < substr.length; i+=2) {
console.log("step", substr[i])
}
在
//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
console.log(substr[i]) //note i returns index
}
对于
for(var i of subs) {
//can use break;
console.log(i); //note i returns value
}
forEach
substr.forEach(function(v, i, a){
//cannot use break;
console.log(v, i, a);
})
【讨论】:
这里不需要 jquery,只需一个 for 循环即可:
var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
alert(substr[i]);
}
【讨论】:
for-loop传统的for-loop 包含三个组件:
这三个组件由; 符号相互分隔。这三个组件的内容都是可选的,这意味着以下是最小的for-loop:
for (;;) {
// Do stuff
}
当然,您需要在 for 循环内的某处包含 if(condition === true) { break; } 或 if(condition === true) { return; } 以使其停止运行。
通常,初始化用于声明索引,条件用于将该索引与最小值或最大值进行比较,事后考虑用于增加索引:
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
for-loop 循环遍历数组遍历数组的传统方式是这样的:
for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}
或者,如果你喜欢向后循环,你可以这样做:
for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}
但是,可能有许多变化,例如。这个:
for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
console.log(value);
}
...或者这个...
var i = 0, length = myArray.length;
for (; i < length;) {
console.log(myArray[i]);
i++;
}
...或者这个:
var key = 0, value;
for (; value = myArray[key++];){
console.log(value);
}
哪个效果最好,很大程度上取决于个人品味和您正在实施的具体用例。
注意:所有浏览器都支持这些变体,包括非常旧的浏览器!
while-loopfor-loop 的一种替代方法是 while-loop。要遍历数组,您可以这样做:
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
注意:
与传统的for-loops 一样,即使是最古老的浏览器也支持while-loops。
此外,每个 while 循环都可以重写为 for-loop。例如,上面的while-loop 的行为方式与for-loop 完全相同:
for(var key = 0;value = myArray[key++];){
console.log(value);
}
for...in 和 for...of
在 JavaScript 中,您也可以这样做:
for (i in myArray) {
console.log(myArray[i]);
}
然而,这应该小心使用,因为它在所有情况下都与传统的for-loop 不同,并且需要考虑潜在的副作用。请参阅 Why is using "for...in" with array iteration a bad idea? 了解更多详情。
作为for...in 的替代品,现在还有for...of。以下示例显示了for...of 循环和for...in 循环之间的区别:
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
}
注意:
您还需要考虑,没有任何版本的 Internet Explorer 支持 for...of(Edge 12+ 支持)并且 for...in 至少需要 IE10。
Array.prototype.forEach()
For-loops 的替代方案是Array.prototype.forEach(),它使用以下语法:
myArray.forEach(function(value, key, myArray) {
console.log(value);
});
注意:
所有现代浏览器以及 IE9+ 都支持Array.prototype.forEach()。
jQuery.each()
除了提到的其他四个选项之外,jQuery 也有自己的 foreach 变体。
它使用以下语法:
$.each(myArray, function(key, value) {
console.log(value);
});
【讨论】:
使用jQuery的each()函数。
这是一个例子:
$.each(currnt_image_list.split(','), function(index, value) {
alert(index + ': ' + value);
});
【讨论】:
使用 jQuery each()。还有其他方法,但每种方法都是为此目的而设计的。
$.each(substr, function(index, value) {
alert(value);
});
并且不要把逗号放在最后一个数字之后。
【讨论】:
带有箭头函数和插值的 ES6 语法:
var data=["a","b","c"];
$(data).each((index, element) => {
console.log(`current index : ${index} element : ${element}`)
});
【讨论】:
您可以使用for() 循环:
var things = currnt_image_list.split(',');
for(var i = 0; i < things.length; i++) {
//Do things with things[i]
}
【讨论】:
试试这个:
$.grep(array, function(element) {
})
【讨论】:
通过具有副作用的数组/字符串进行迭代的替代方法
var str = '21,32,234,223';
var substr = str.split(',');
substr.reduce((a,x)=> console.log('reduce',x), 0) // return undefined
substr.every(x=> { console.log('every',x); return true}) // return true
substr.some(x=> { console.log('some',x); return false}) // return false
substr.map(x=> console.log('map',x)); // return array
str.replace(/(\d+)/g, x=> console.log('replace',x)) // return string
【讨论】:
for(var key in substr)
{
// do something with substr[key];
}
【讨论】:
$.map(data,function(elem){
console.log(elem);
})
【讨论】: