在Java中,可以使用for循环遍历数组中的对象,如下所示:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
我可以在JavaScript中做同样的事情吗?
在Java中,可以使用for循环遍历数组中的对象,如下所示:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
我可以在JavaScript中做同样的事情吗?
当前回答
嗯,这个怎么样:
for (var key in myStringArray) {
console.log(myStringArray[key]);
}
其他回答
这个答案为循环和数组函数提供了一种替代方法,以遍历数组。
在某些情况下,在常规循环和回调上使用递归实现是有意义的。特别是,如果必须使用多个数组或嵌套数组。避免编写嵌套循环来访问多个数组中的数据。我还发现这段代码更容易读写。
/**
array is the array your wish to iterate.
response is what you want to return.
index increments each time the function calls itself.
**/
const iterateArray = (array = [], response = [], index = 0) => {
const data = array[index]
// If this condition is met. The function returns and stops calling itself.
if (!data) {
return response
}
// Do work...
response.push("String 1")
response.push("String 2")
// Do more work...
// THE FUNCTION CALLS ITSELF
iterateArray(data, response, index+=1)
}
const mainFunction = () => {
const text = ["qwerty", "poiuyt", "zxcvb"]
// Call the recursive function
const finalText = iterateArray(text)
console.log("Final Text: ", finalText()
}
假设传递给iterateArray的数组包含对象而不是字符串。每个对象中都包含另一个数组。您必须运行嵌套循环才能访问内部数组,但如果递归迭代,则不必如此。
您还可以将iterateArray设置为Promise。
const iterateArray = (array = [], response = []) =>
new Promise(async (resolve, reject) => {
const data = array.shift()
// If this condition is met, the function returns and stops calling itself.
if (!data) {
return resolve(response)
}
// Do work here...
const apiRequestData = data.innerArray.find((item) => {
item.id === data.sub_id
})
if (apiRequestData) {
try {
const axiosResponse = await axios.post(
"http://example.com",
apiRequestData
)
if (axiosResponse.status === 200) {
response.push(apiRequestData)
} else {
return reject("Data not found")
}
} catch (error) {
reject(error)
}
} else {
return reject("Data not found")
}
// THE FUNCTION RESOLVES AND CALLS ITSELF
resolve(iterateArray(data, response))
})
JavaScript中的数组遍历作弊表
给定一个数组,可以通过以下多种方式之一遍历它。
1.经典for loop
const myArray=['Hello','World'];for(设i=0;i<myArray.length;i++){console.log(myArray[i]);}
2.用于。。。属于
const myArray=['Hello','World'];for(myArray的常量项){console.log(项);}
3.Array.prototype.forEach()
const myArray=['Hello','World'];myArray.forEach(项=>{console.log(项);});
4.while循环
const myArray=['Hello','World'];设i=0;while(i<myArray.length){console.log(myArray[i]);i++;}
5.do…while循环
const myArray=['Hello','World'];设i=0;做{console.log(myArray[i]);i++;}而(i<myArray.length);
6.队列样式
const myArray=['Hello','World'];while(myArray.length){console.log(myArray.shift());}
7.堆栈样式
注:该列表在本页中以相反的方式打印。const myArray=['Hello','World'];while(myArray.length){console.log(myArray.pop());}
它不是100%相同,但相似:
var myStringArray=['Hello','World'];//数组使用[]而不是{}for(myStringArray中的var i){console.log(i+'->'+myStringArray[i]);//我是索引/键,而不是项目}
Opera、Safari、Firefox和Chrome现在都共享一组增强的Array方法来优化许多常见循环。
您可能不需要所有这些,但它们可能非常有用,或者如果每个浏览器都支持它们,它们就会非常有用。
Mozilla实验室发布了他们和WebKit都使用的算法,因此您可以自己添加它们。
筛选器返回满足某个条件或测试的项目数组。
如果每个数组成员都通过测试,则every返回true。
如果有人通过测试,则返回true。
forEach在每个数组成员上运行一个函数,不返回任何内容。
map类似于forEach,但它返回每个元素的操作结果数组。
这些方法都将一个函数作为其第一个参数,并有一个可选的第二个参数,这是一个对象,当数组成员循环通过该函数时,您希望将其范围强加给数组成员。
忽略它,直到你需要它。
indexOf和lastIndexOf查找与其参数完全匹配的第一个或最后一个元素的适当位置。
(function(){
var p, ap= Array.prototype, p2={
filter: function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
},
every: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in this && !fun.call(scope, this[i], i, this))
return false;
++i;
}
return true;
}
return null;
},
forEach: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
fun.call(scope, this[i], i, this);
}
++i;
}
}
return this;
},
indexOf: function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what)
return i;
++i;
}
return -1;
},
lastIndexOf: function(what, i){
var L= this.length;
i= i || L-1;
if(isNaN(i) || i>= L)
i= L-1;
else
if(i< 0) i += L;
while(i> -1){
if(this[i]=== what)
return i;
--i;
}
return -1;
},
map: function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
},
some: function(fun, scope){
var i= 0, L= this.length;
if(typeof fun== 'function'){
while(i<L){
if(i in this && fun.call(scope, this[i], i, this))
return true;
++i;
}
return false;
}
}
}
for(p in p2){
if(!ap[p])
ap[p]= p2[p];
}
return true;
})();
JavaScript中有多种循环数组的方法。
通用循环:
var i;
for (i = 0; i < substr.length; ++i) {
// Do something with `substr[i]`
}
每个ES5:
substr.forEach(function(item) {
// Do something with `item`
});
jQuery.each:
jQuery.each(substr, function(index, item) {
// Do something with `item` (or `this` is also `item` if you like)
});
查看此信息以获取详细信息,或者您也可以检查MDN是否在JavaScript中循环遍历数组,并使用jQuery检查每个数组的jQuery。