在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中做同样的事情吗?
当前回答
例如,我在Firefox控制台中使用了:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
您可以使用querySelectorAll获得相同的结果
document.querySelectorAll('pre').forEach((e)=>{console.log(e.textContent);})<pre>文本1</pre><pre>文本2</pre><pre>文本3</pre>
其他回答
6种不同的方法循环遍历阵列
可以通过许多不同的方法循环遍历数组。我从上到下整理了我最喜欢的6种方法。
1.使用for循环
当它只是在数组中循环时,for循环是我的首选。
让数组=[1,2,3,4,5];for(设i=0;i<array.length;i++){console.log(array[i]);}
2.使用forEach循环
forEach循环是一种在数组中循环的现代方式。此外,它还提供了对阵列和元素的更多灵活性和控制。
让数组=[1,2,3,4,5];array.forEach((元素)=>{console.log(元素);});
3.用于。。。属于
对于of循环允许您直接访问数组元素。
让数组=[1,2,3,4,5];for(数组的let元素){console.log(元素);}
4.用于。。。在回路中
对于中提供了一个键,您可以使用该键访问数组元素。
让数组=[1,2,3,4,5];for(数组中的let索引){console.log(array[index]);}
5.使用while循环
而loop也可以用于循环通过阵列。
让数组=[1,2,3,4,5];let length=array.length;而(长度>0){console.log(array[array.length-length]);长度--;}
6.使用do…while循环
同样,我使用do…while循环
让数组=[1,2,3,4,5];let length=array.length;做{console.log(array[array.length-length]);长度--;}而(长度>0)
这个答案为循环和数组函数提供了一种替代方法,以遍历数组。
在某些情况下,在常规循环和回调上使用递归实现是有意义的。特别是,如果必须使用多个数组或嵌套数组。避免编写嵌套循环来访问多个数组中的数据。我还发现这段代码更容易读写。
/**
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))
})
阵列循环:
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
有一种方法可以在循环中的隐式作用域很小的情况下实现,并去掉额外的变量。
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等迭代器方法。