本文實例講述了JavaScript數(shù)組各種常見用法。分享給大家供大家參考。具體如下:
運行效果如下圖所示:
具體代碼如下:
輸出
ap[0].innerHTML = aTmp.join()
};
//刪除/添加最后一項
aInput[1].onclick = function ()
{
aTmp = getArray(ap[0].innerHTML);
bS2 ?
//刪除最后一項, pop()方法
(aTmp.pop(), this.value = this.value.replace("刪除","添加"), bS2 = false) :
//添加最后一項, push()方法
(aTmp.push("December(12)"), this.value = this.value.replace("添加","刪除"), bS2 = true);
//輸出
ap[0].innerHTML = aTmp.join()
};
//復(fù)制, concat()方法
aInput[2].onclick = function ()
{
aTmp = getArray(ap[1].innerHTML);
//輸出
ap[1].innerHTML = aTmp.concat(aTmp).toString().replace(/s/g,"")
};
//還原, 利用數(shù)組的 length 特點
aInput[3].onclick = function ()
{
aTmp = getArray(ap[1].innerHTML);
//設(shè)置數(shù)組長度
aTmp.length = 10;
//輸出
ap[1].innerHTML = aTmp.join()
};
//第三組數(shù)據(jù)還原
aInput[4].onclick = function ()
{
aTmp = ["red","green","blue","white","yellow","black","brown"];
//輸出
ap[2].innerHTML = aTmp.join()
};
//刪除前三項
aInput[5].onclick = function ()
{
aTmp = getArray(ap[2].innerHTML);
//刪除, 0開始, 刪除3個
aTmp.splice(0, 3);
//輸出
ap[2].innerHTML = aTmp.join()
};
//刪除第二至三項
aInput[6].onclick = function ()
{
aTmp = getArray(ap[2].innerHTML);
//刪除, 2開始, 刪除2個
aTmp.splice(1, 2);
//輸出
ap[2].innerHTML = aTmp.join()
};
//在第二頂后插入"orange", "purple"
aInput[7].onclick = function ()
{
aTmp = getArray(ap[2].innerHTML);
//插入, 2開始, 插入"orange", "purple"
aTmp.splice(1, 0, "orange", "purple");
//輸出
ap[2].innerHTML = aTmp.join()
};
//替換第二項和第三項
aInput[8].onclick = function ()
{
aTmp = getArray(ap[2].innerHTML);
//插入, 2開始替換
aTmp.splice(1, 2, "#009900", "#0000ff");
//輸出
ap[2].innerHTML = aTmp.join()
};
//將p中的內(nèi)容轉(zhuǎn)為數(shù)組
//str p對象
function getArray(str)
{
aTmp.length = 0;
str = str.split(",");
for (var i in str)aTmp.push(str[i]);
return aTmp
}
}
</script>
</head>
<body>
<p>January(1),February(2),March(3),April(4),May(5),June(6),July(7),Aguest(8),September(9),October(10),November(11),December(12)</p>
<input type="button" value="刪除January(1)" />
<input type="button" value="刪除December(12)" />
<p>0,1,2,3,4,5,6,7,8,9</p>
<input type="button" value="復(fù)制" />
<input type="button" value="還原" />
<p>red,green,blue,white,yellow,black,brown</p>
<input type="button" value="還原" />
<input type="button" value="刪除前三項" />
<input type="button" value="刪除第二至三項" />
<input type="button" value="在第二項后插入(orange, purple)" />
<input type="button" value="替換第二項和第三項" />
</body>
</html>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com