1. 程式人生 > >JavaScript 循環語句

JavaScript 循環語句

list 變形金剛 循環語句 ... 實例 document cto javascrip border

1.for循環

for(......){
.........;
}

實例:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>cycle</title>
<script type="text/javascript">

/*var aList01 = [‘a‘,‘b‘,‘c‘,‘d‘];
var aLen = aList01.length;
for(var i=0;i<aLen;i++){
    alert(aList01[i]);
}*/
window.onload = function(){
    var oUl = document.getElementById(‘ul‘);
    var aList = [‘美人魚‘,‘大黃蜂‘,‘變形金剛‘,‘海王‘];
    var sTr = ‘‘;
    for(var i=0;i<aList.length;i++){
        sTr += ‘<li>‘ + aList[i] + ‘</li>‘;
    }
    /*alert(sTr);*/
    oUl.innerHTML = sTr;
}
</script>

<style type="text/css">

.ulcon{
    width: 300px;
    height: 300px;
    list-style: none;
    margin: 50px auto 0;

}
.ulcon li{
    height: 70px;
    line-height: 70px;
    border-bottom: 1px dotted #000;

}
</style>

</head>

<body>

<ul class="ulcon" id="ul">
    <!--<li>美人魚</li>
    <li>美人魚</li>
    <li>美人魚</li>
    <li>美人魚</li>-->
</ul>

</body>
</html>

技術分享圖片

2.while循環

var ....
while(....){
.......
i++;
}

3.數組去重

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>repea</title>
<script type="text/javascript">

var aList01 = [1,2,4,5,5,8,4,7,8,4,6,1,9,5,4,9];
var iLen = aList01.length;
var aList02 = [];
for(var i=0;i<iLen;i++){
    if(aList01.indexOf(aList01[i])==i){  /*每個重復數字的位置是第一個*/
        aList02.push(aList01[i]);
    }
}
alert(aList02);
</script>

</head>

<body>
</body>
</html>

JavaScript 循環語句