我有一个简单的javascript示例,其中包含带有let的for循环。在这里,我需要用1来初始化i
值,例如1,2,3等。现在就像01,11,21,31等。在这里,我不应该在for循环中更改任何内容。
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
for (let i in cars) {
text += cars[i] + "<br>";
console.log(i + 1);
}
document.getElementById("demo").innerHTML = text;
<h2>JavaScript Loops</h2>
<p id="demo"></p>
答案 0 :(得分:1)
for..in
循环将遍历数组,这意味着变量i
将一个一个地取每个字符串的值
要实现您的目标,有一种简单的方法,只需一行代码:
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
const text = cars.map(car => car + "<br>").join('');
document.getElementById("demo").innerHTML = text;
<h2>JavaScript Loops</h2>
<p id="demo"></p>
map
函数将用另一个元素更改数组中的每个元素,结果如下:["BMW<br>", "Volvo<br>", "Saab<br>", "Ford<br>", "Fiat<br>", "Audi<br>"]
然后,join
将获取数组中的所有字符串,并将它们放在一起
答案 1 :(得分:1)
尽管有许多惊人的答案,但我仍然想分享/添加我的答案
使用“for…in” with array iteration
是个坏主意吗?为什么?在此处阅读detailed answers
回到意外行为的原因。
For-in旨在主要与对象一起使用,作为键
现在,由于您要获取数组,
for (let i in cars) {
console.log(i)
}
将日志字符串“ 1”,“ 2”,“ 3” 代替整数 1、2、3 。为什么? Read here about the crazy nature of javascript
因此,最好的使用方法是(从以上答案中复制)
//Method1
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
const text = cars.map(car => car + "<br>").join('');
document.getElementById("demo").innerHTML = text;
//Method 2
const cars1 = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
let text1 = "";
for (let i = 1; i < cars1.length; i ++){
text1 += cars1[i] + "<br>";
console.log(i + 1);
}
document.getElementById("demo1").innerHTML = text1;
<h2>JavaScript Loops</h2>
<div id="demo"></div>
<h2>JavaScript Loops 1</h2>
<div id="demo1"></div>
答案 2 :(得分:0)
forEach
循环将是一种更好且更清洁的方法。运行下面的代码片段,或检查此jsFiddle以查看如何使用forEach
遍历您的汽车阵列:
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var x = document.getElementById("demo");
text = "";
cars.forEach(function(car){
return text += car + '<br/>';
});
x.innerHTML = text;
<h2>JavaScript Loops</h2>
<div id="demo"></div>
如果您愿意使用新的JavaScript ES6语法,则可以进一步缩短上述代码:
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
const x = document.getElementById("demo");
text = "";
cars.forEach(car => text += `${car}<br/>`);
x.innerHTML = text;
答案 3 :(得分:0)
您可以使用普通的for loop
。您还可以删除i
的第一个声明,因为您已经拥有let i
。
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
for (let i = 1; i < cars.length; i ++){
text += cars[i] + "<br>";
console.log(i + 1);
}
document.getElementById("demo").innerHTML = text;
<h2>JavaScript Loops</h2>
<p id="demo"></p>
答案 4 :(得分:0)
我不明白为什么需要偏移量,因为数组从零开始。
但是您得到的结果为01,21,32,因为您打印0 + 1 = 01、1 + 1 = 11不会递增。
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
for (let i in cars) {
text += cars[i] + "<br>";
i++;
console.log(i);
}
您可以像这样实现相同的结果:
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
cars.forEach (function(item){
text += item + "<br>";
});