[英]How to loop through array in jQuery?
我正在尝试遍历一个数组。 我有以下代码:
var currnt_image_list= '21,32,234,223';
var substr = currnt_image_list.split(','); // array 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
的含义没有问题,没有不必要的函数调用开销(例如,理论上更快,但实际上你会有有这么多元素,你很可能会遇到其他问题; 细节)。
forEach
: 从 ECMAScript5 开始,数组有一个forEach
函数,这使得遍历数组变得容易:
substr.forEach(function(item) {
// do something with `item`
});
(注意:还有很多其他函数,而不仅仅是forEach
;有关详细信息,请参阅上面引用的答案。)
优点:声明性,如果你有手,可以为迭代器使用预建函数,如果你的循环体很复杂,函数调用的范围有时是有用的,在你的包含范围中不需要i
变量。
缺点:如果您在使用this
中包含代码,你想用this
你中forEach
回调,你必须要么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
循环for..in
对象的可枚举属性名称(而不是数组的索引)。 由于数组是对象,并且默认情况下它们唯一可枚举的属性是索引,因此它似乎主要是在平淡的部署中工作。 但这并不是一个安全的假设,您可以将其用于此目的。 这是一个探索: http : //jsbin.com/exohi/3
我应该软化上面的“不要”。 如果您正在处理稀疏数组(例如,该数组共有 15 个元素,但由于某种原因它们的索引散布在 0 到 150,000 的范围内,因此length
为 150,001),并且如果您使用适当的保护措施,例如hasOwnProperty
和检查属性名称确实是数字(参见上面的链接), for..in
是避免大量不必要循环的一种非常合理的方法,因为只会枚举填充的索引。
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
}
为每个
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
循环传统的for
循环包含三个组件:
这三个组件由一个;
相互隔开;
符号。 这三个组件中的每一个的内容都是可选的,这意味着以下是最小的for
-loop 可能:
for (;;) {
// Do stuff
}
当然,你需要包含一个if(condition === true) { break; }
if(condition === true) { break; }
或者一个if(condition === true) { return; }
if(condition === true) { return; }
内某处for
-loop得到它停止运行。
但是,通常初始化用于声明索引,条件用于将该索引与最小值或最大值进行比较,事后考虑用于增加索引:
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
for
循环遍历数组循环遍历数组的传统方法是:
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
循环 for
循环的一种替代方法是while
循环。 要遍历数组,您可以这样做:
var key = 0; while(value = myArray[key++]){ console.log(value); }
注意:
与传统的for
-loops 一样, while
-loops 甚至被最古老的浏览器支持。
此外,每个 while 循环都可以重写为for
循环。 例如,上面的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
循环不同,并且需要考虑潜在的副作用。 请参阅为什么在数组迭代中使用“for...in”是个坏主意? 了解更多详情。
作为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
循环的替代方法是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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.