说明:代码取自网络,注释为笔者学习时添加!
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>数组方法的使用</title> <style> div{ color:green; padding:10px 15px; margin:12px 0; background:#f0f0f0;/*白色*/ border:1px solid #333;/*黑色*/ font:12px/1.5 Courier New;/*行高18*/ word-wrap:break-word; } </style> <script> window.onload = function () { var aDiv = document.getElementsByTagName("div"); var aInput = document.getElementsByTagName("input"); var i = 0; var bS1 = bS2 = true; var aTmp = [];//空数组 aInput[0].onclick = function () { aTmp = getArray(aDiv[0].innerHTML); bS1 ? //删除第一项,shift()方法 (aTmp.shift(), this.value = this.value.replace("删除", "添加"), bS1 = false) : //添加第一项,unshift()方法 (aTmp.unshift("January(1)"), this.value = this.value.replace("添加", "删除"), bS1 = true); //输出 aDiv[0].innerHTML = aTmp.join(); }; //删除/添加最后一项 aInput[1].onclick = function () { aTmp = getArray(aDiv[0].innerHTML); bS2 ? (aTmp.pop(), this.value = this.value.replace("删除", "添加"), bS2 = false) : (aTmp.push("December(12"), this.value = this.value.replace("添加", "删除"), bS2 = true); aDiv[0].innerHTML = aTmp.join(); }; //复制,concat()方法 aInput[2].onclick = function () { aTmp = getArray(aDiv[1].innerHTML); aDiv[1].innerHTML = aTmp.concat(aTmp).toString().replace(/s/g, "");//调用concat合并,toString转换为字符串,再替换掉所有空格 }; aInput[3].onclick = function () { aTmp = getArray(aDiv[1].innerHTML);//获取内容 aTmp.length = 10; aDiv[1].innerHTML = aTmp.join(); }; aInput[4].onclick = function () { aTmp = ["red", "green", "blue", "white", "yellow", "black", "brown"]; aDiv[2].innerHTML = aTmp.join(); }; aInput[5].onclick = function () { aTmp = getArray(aDiv[2].innerHTML); aTmp.splice(0, 3); aDiv[2].innerHTML = aTmp.join(); }; aInput[6].onclick = function () { aTmp = getArray(aDiv[2].innerHTML); aTmp.splice(1, 2); aDiv[2].innerHTML = aTmp.join(); }; aInput[7].onclick = function () { aTmp.getArray(aDiv[2].innerHTML); aTmp.splice(1, 0, "orange", "purple"); aDiv[2].innerHTML = aTmp.join(); }; aInput[8].onclick = function () { aTmp = getArray(aDiv[2].innerHTML); aTmp.splice(1, 2, "#009900", "#0000ff"); aDiv[2].innerHTML = aTmp.join(); }; function getArray(str) { aTmp.length = 0; str = str.split(","); for (var i in str) aTmp.push(str[i]); return aTmp; } } </script> </head> <body> <div>January(1),February(2),March(3),April(4),May(5),June(6),July(7),August(8),september(9),October(10),November(11),December(12)</div> <input type="button" value="删除January(1)" /> <input type="button" value="删除December(12)" /> <div>0,1,2,3,4,5,6,7,8,9</div> <input type="button" value="复制" /> <input type="button" value="还原" /> <div>red,green,blue,white,yellow,black,brown</div> <input type="button" value="还原" /> <input type="button" value="删除前三项" /> <input type="button" value="删除第二至第三项" /> <input type="button" value="在第二项后插入(orange, purple)" /> <input type="button" value="替换第二项和第三项" /> </body> </html>