当前位置:Gxlcms > JavaScript > 总结JavaScript数组各种常见用法

总结JavaScript数组各种常见用法

时间:2021-07-01 10:21:17 帮助过:6人阅读

本文实例讲述了JavaScript数组各种常见用法。分享给大家供大家参考。具体如下:

运行效果如下图所示:

具体代码如下:

输出 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() }; //复制, concat()方法 aInput[2].onclick = function () { aTmp = getArray(ap[1].innerHTML); //输出 ap[1].innerHTML = aTmp.concat(aTmp).toString().replace(/s/g,"") }; //还原, 利用数组的 length 特点 aInput[3].onclick = function () { aTmp = getArray(ap[1].innerHTML); //设置数组长度 aTmp.length = 10; //输出 ap[1].innerHTML = aTmp.join() }; //第三组数据还原 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中的内容转为数组 //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="复制" /> <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>

以上就是总结JavaScript数组各种常见用法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行