【前端学习-循环语句】js基础学习笔记
程序员文章站
2022-05-07 19:34:04
...
1.for循环
<script >
names=["李华","Volvo","王晶","Ford"];//数组
for (var i=0;i<names.length;i++)//数组的长度用names.length来获取
{
document.write(names[i] + "<br>");
}
</script>
<body>
<h2 id="demo"></h2>
<button οnclick="myfunction()">点击这里</button>
</body>
<script >
function myfunction()
{
var x="";
for(var i=0;i<5;i++)
{
x=x+"该数字为:"+i+"<br>";
}
document.getElementById('demo').innerHTML=x;
}
</script>
效果图:
2.for/in循环
for (变量 in 对象/数组)
{
在此执行代码
}
<script >
var x="";
i=[1,2,3,4,5,6];
var j;
for(j in i)//j是变量,i是数组
{
document.write(i[j]+" ,");
}
</script>
效果图:
/20200708220451695.png)<script>
var txt = "";
var person = {fname:"Bill", lname:"Gates", age:62};
var x;
for (x in person) //x是变量,person是对象
{
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
上一篇: html中添加js的三种方式
下一篇: 前端基础学习03
推荐阅读