我从w3school学习javascript。我得到了这个例子。有没有可能如何编写这个代码“更好”?这不是过时的吗?
谢谢
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
答案 0 :(得分:0)
不知道,如果它实际上更好,但无论如何它更短,并使用更多“现代”功能。
let fruits = ["Banana", "Orange", "Apple", "Mango"],
text = fruits.map( (fruit) => '<li>' + fruit + '</li>' );
document.querySelector('#demo').innerHTML = '<ul>' + text.join('') + '</ul>';
答案 1 :(得分:0)
你可以在你的html中创建
<ul id="fruitUl"></ul>
然后
text="";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
$("fruitUl").append(text);
这也是古董。这只是我的意见。
答案 2 :(得分:-1)
我会建议这个
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fVar = 0;
var fLen = fruits.length;
var htmlContent = "<ul>";
for (fVar = 0; fVar < fLen; fVar++) {
htmlContent += "<li>" + fruits[fVar] + "</li>";
}
htmlContent += "</ul>";
document.getElementById("demo").innerHTML = htmlContent;
</script>
</body>
</html>
这只是了解阵列概念的基本代码。