在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中做同样的事情吗?
当前回答
var obj = ["one","two","three"];
for(x in obj){
console.log(obj[x]);
}
其他回答
阵列循环:
for(var i = 0; i < things.length; i++){
var thing = things[i];
console.log(thing);
}
对象循环:
for(var prop in obj){
var propValue = obj[prop];
console.log(propValue);
}
使用while循环。。。
var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
console.log(item);
}
它记录:“一”、“二”和“三”
对于相反的顺序,一个更有效的循环:
var items = ['one', 'two', 'three'], i = items.length;
while(i--){
console.log(items[i]);
}
它记录:“三”、“二”和“一”
或者经典的for循环:
var items = ['one', 'two', 'three']
for(var i=0, l = items.length; i < l; i++){
console.log(items[i]);
}
它记录:“一”、“两”、“三”
参考资料:谷歌闭包:如何不编写JavaScript
这个答案为循环和数组函数提供了一种替代方法,以遍历数组。
在某些情况下,在常规循环和回调上使用递归实现是有意义的。特别是,如果必须使用多个数组或嵌套数组。避免编写嵌套循环来访问多个数组中的数据。我还发现这段代码更容易读写。
/**
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:
const students = ["Arun","Jos","John","Kiran"]
for (var index = 0; index < students.length; index++) {
console.log(students[index]);
}
方法2:
students.forEach((学生,索引)=>console.log(学生));
方法3:
for (const student of students) {
console.log(student);
}
有一种方法可以在循环中的隐式作用域很小的情况下实现,并去掉额外的变量。
var i = 0,
item;
// Note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
item; // This is the string at the index.
}
或者如果你真的想得到id并有一个真正经典的for循环:
var i = 0,
len = myStringArray.length; // Cache the length
for ( ; i < len ; i++ ){
myStringArray[i]; // Don't use this if you plan on changing the length of the array
}
现代浏览器都支持Array原型上的Each、map、reduce、filter等迭代器方法。