对于JavaScript中数组上的每个
如何使用JavaScript循环遍历数组中的所有条目 我以为是这样的:对于JavaScript中数组上的每个,javascript,arrays,loops,foreach,iteration,Javascript,Arrays,Loops,Foreach,Iteration,如何使用JavaScript循环遍历数组中的所有条目 我以为是这样的: forEach(instance in theArray) var myArray = [1, 2, 3]; myArray = myArray.map( (item) => { return item + 1; } ); console.log(myArray); // [2, 3, 4] for (let i=0; i<theArray.length; i++) { console.
forEach(instance in theArray)
var myArray = [1, 2, 3];
myArray = myArray.map(
(item) => {
return item + 1;
}
);
console.log(myArray); // [2, 3, 4]
for (let i=0; i<theArray.length; i++) {
console.log(i); // i will have the value of each index
}
其中数组是我的数组,但这似乎不正确。TL;DR
- 您的最佳赌注通常是
- 用于of
循环的(仅限ES2015+)-简单且异步
-友好
forEach
(仅限ES5+)(或其亲属一些之类)不异步-友好(但请参见详细信息)
用于
循环的简单老式的异步友好
用于具有保护措施的in
,异步
-友好型- 不要在中使用
,除非您使用时有安全措施,或者至少知道它可能会咬到您的原因 - 如果你没有使用它的返回值,就不要使用
map
(很遗憾,有人在那里教
[/],好像它是map
——但是,如果你没有使用它创建的数组,就不要使用forEach
)map
- 如果回调执行异步工作,并且希望
等待该工作完成(因为它不会),则不要使用forEach
forEach
JavaScript在数组和类似数组的对象之间具有强大的循环语义。我将答案分为两部分:用于真正数组的选项,以及与数组类似的选项,例如
参数
对象、其他iterable对象(ES2015+)、DOM集合等
好的,让我们看看我们的选择:
对于实际阵列
您有五个选项(两个基本上永远支持,另一个由ECMAScript 5[“ES5”]添加,另外两个在ECMAScript 2015(“ES2015”,也称为“ES6”)中添加):
进行of
(隐式使用迭代器)(ES2015+)forEach
和相关(ES5+)
用于in
进行of
(隐式使用迭代器)(ES2015+)
ES2015添加到JavaScript中。数组是可编辑的(字符串、Map
s和Set
s以及DOM集合和列表也是可编辑的,您将在后面看到)。可编辑对象为其值提供迭代器。新的for of
语句循环遍历迭代器返回的值:
常数a=[“a”,“b”,“c”];
对于(a的const val){//如果愿意,可以用'let'代替'const'
控制台日志(val);
}
//a
//b
//c注意这个答案已经过时了。要了解更现代的方法,请查看。感兴趣的方法可能是:
- 弗雷奇
- 地图
- 滤器
- 拉链
- 减少
- 每一个
- 一些
在中迭代数组的标准方法是一个普通的
for
-循环:
var length = arr.length,
element = null;
for (var i = 0; i < length; i++) {
element = arr[i];
// Do something with element
}
var length=arr.length,
元素=空;
对于(变量i=0;i
但是,请注意,只有当您有一个密集的数组,并且每个索引都被一个元素占用时,这种方法才是好的。如果数组是稀疏的,那么使用这种方法您可能会遇到性能问题,因为您将迭代许多在数组中并不真正存在的索引。在这种情况下,对于..in-循环使用for可能更好er idea。但是,您必须使用适当的保护措施来确保仅对数组的所需属性(即数组元素)进行操作,因为在传统浏览器中,..in
-循环的也将枚举,或者如果附加属性定义为可枚举的
在中,阵列原型上将有一个forEach方法,但传统浏览器不支持它。因此,为了能够一致地使用它,您必须有一个支持它的环境(例如,对于服务器端JavaScript),或者使用“Polyfill”。但是,此功能的Polyfill很简单,因为它使代码更易于阅读,所以它是一个很好的Polyfill。如果要在数组上循环,请使用标准的三部分进行循环
for (var i = 0; i < myArray.length; i++) {
var arrayItem = myArray[i];
}
for(var i=0;i
通过缓存myArray.length
或向后迭代,您可以获得一些性能优化。在本机中,每个循环没有任何。您可以使用库来获得此功能(我建议),对循环使用简单的
for (var instance in objects) {
...
}
但是,请注意,可能有理由对
循环使用更简单的(请参阅堆栈溢出问题)
var实例;
对于(var i=0;i
一些风格的语言使用foreach
循环枚举。在JavaScript中,这是通过以下方式完成的:
有一个陷阱。for..in
将循环遍历对象的每个可枚举成员及其原型上的成员。为避免读取通过对象原型继承的值,只需检查属性是否属于对象:
for (i in obj) {
if (obj.hasOwnProperty(i)) {
//do stuff
}
}
此外,还向Array.prototype添加了一个方法,该方法可用于使用calback对数组进行枚举(文档中有polyfill,因此您仍然可以在较旧的浏览器中使用它):
需要注意的是,Array.prototype.forEach
在回调返回false
时不会中断,并提供它们自己的变量
arr.forEach(function (val, index, theArray) {
//do stuff
});
var x;
while(x = y.pop()){
alert(x); //do something
}
function forEach(list,callback) {
var length = list.length;
for (var n = 0; n < length; n++) {
callback.call(list[n]);
}
}
var myArray = ['hello','world'];
forEach(
myArray,
function(){
alert(this); // do something
}
);
var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});
var array = new Array();
array[1] = "Hello";
array[7] = "World";
array[11] = "!";
for(var i in array){
var el = array[i];
//If you want 'i' to be INT just put parseInt(i)
//Do something with el
}
function foreach(array, call){
for(var i in array){
call(array[i]);
}
}
function foreach(array, call){
for(var i in array){
if(call(array[i]) == false){
break;
}
}
}
foreach(array, function(el){
if(el != "!"){
console.log(el);
} else {
console.log(el+"!!");
}
});
//Hello
//World
//!!!
var a = [3,2];
$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3
function each( fn, data ) {
if(typeof fn == 'string')
eval('fn = function(data, i){' + fn + '}');
for(var i=0, L=this.length; i < L; i++)
fn.call( this[i], data, i );
return this;
}
Array.prototype.each = each;
var arr = [];
[1, 2, 3].each( function(a){ a.push( this * this}, arr);
arr = [1, 4, 9]
each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');
each.call(document.getElementsByTagName('p'),
"if( i % 2 == 0) this.className = data;",
'red'
);
each.call(document.querySelectorAll('p.blue'),
function(newClass, i) {
if( i < 20 )
this.className = newClass;
}, 'green'
);
var data = [1, 2, 3, 4, 5, 6, 7];
var newData = $.map(data, function(element) {
if (element % 2 == 0) {
return element;
}
});
// newData = [2, 4, 6];
for (var i = array.length; i--; ) {
// process array[i]
}
for (var i = 0; i < array.length; i++) { ... } // Forwards
for (var i = array.length; i--; ) { ... } // Reverse
for (var i = array.length; i --> 0 ;) {
var temp = [1, 2, 3];
angular.forEach(temp, function(item) {
//item will be each element in the array
//do something
});
var temp = [1, 2, 3];
var temp2 = [];
angular.forEach(temp, function(item) {
this.push(item); //"this" refers to the array passed into the optional third parameter so, in this case, temp2.
}, temp2);
angular.forEach(temp, function(item) {
temp2.push(item);
});
angular.forEach(obj1.results, function(result1) {
angular.forEach(obj2.results, function(result2) {
if (result1.Value === result2.Value) {
//do something
}
});
});
//exact same with a for loop
for (var i = 0; i < obj1.results.length; i++) {
for (var j = 0; j < obj2.results.length; j++) {
if (obj1.results[i].Value === obj2.results[j].Value) {
//do something
}
}
}
[1,2,3].some(function(number) {
return number === 1;
});
var foo = [object,object,object];
for (var i = foo.length, item; item = foo[--i];) {
console.log(item);
}
['C', 'D', 'E'].forEach(function(element, index) {
console.log(element + " is #" + (index+1) + " in the musical scale");
});
// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale
// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
return elem.toUpperCase();
});
// Output: ['BOB', 'JOE', 'JEN']
[1,2,3,4].reduce(function(previous, current) {
return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10
// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];
ages.every(function(elem) {
return elem >= 18;
});
// Output: false
// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
return (elem % 2 == 0)
});
// Output: [2,4,6]
myArray.forEach(
(item) => {
// Do something
console.log(item);
}
);
var myArray = [1, 2, 3];
myArray = myArray.map(
(item) => {
return item + 1;
}
);
console.log(myArray); // [2, 3, 4]
[].forEach.call(arrayName,function(value,index){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
$("#ul>li").each(function(**index, value**){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
theArray.forEach ( element => {
console.log(element);
});
for(let idx = 0; idx < theArray.length; idx++){
let element = theArray[idx];
console.log(element);
}
let theArray= [1,3,2];
theArray.forEach((element) => {
// Use the element of the array
console.log(element)
}
1
3
2
for (let i=0; i<theArray.length; i++) {
console.log(i); // i will have the value of each index
}
for(var i = 0; i < 5; i++){
console.log(i);
}
// Output: 0,1,2,3,4
let obj = {"a":1, "b":2}
for(let k in obj){
console.log(k)
}
// Output: a,b
let array = [1,2,3,4]
array.forEach((x) => {
console.log(x);
})
// Output: 1,2,3,4
let array = [1,2,3,4]
for(let x of array){
console.log(x);
}
// Output: 1,2,3,4
let x = 0
while(x < 5){
console.log(x)
x++
}
// Output: 1,2,3,4
let x = 0
do{
console.log(x)
x++
}while(x < 5)
// Output: 1,2,3,4