时间:2021-07-01 10:21:17 帮助过:2人阅读
1、队尾插入push
var colors = ["red","green"]; colors.push("black"): console.log(colors); //["red","green","black"]
2、队尾删除并返回删除的最后一项pop
var colors = ["red","green","black"]; var item = colors.pop(); console.log(item); //"black"
3、队首插入unshift()
var colors = ["red","green"]; colors.unshift("black"); var item = colors.pop(); console.log(item); //"black"
4、队首删除shift()
var colors = ["red","green","black"]; colors.shift(); console.log(colors); //["green","black"]
5、数组一添加数组二concat()
var colors = ["red","green","black"]; var colors2 = colors.concat("yellow",["blue","brown"]); console.log(colors); //["red","green","black"] console.log(colors2); //["red","green","black","yellow","blue","brown"]
6、数组的截取slice()
只传一个参数:从数组这个参数的下标开始截取一直到数组结束。
var colors = ["red","green","black"]; colors.slice(1); //["green","black"] console.log(colors); //["red","green","black"]
传两个参数:第一个是截取开始的位置,第二个是截取结束的位置
var colors = ["red","green","black","yellow","blue","brown"]; colors.slice(1,3)//从位置1开始,到位置2结束["green","black"];
7、数组的splice()方法
有三种用法:
删除:可以删除任意数量的项,只需指定两个参数:第一个参数为删除开始的位置,第二个参数为删除项数。
插入:可以向指定位置插入任意数量的项,只需提供3个参数:起始位置、0(要删除的项数)和要插入的项。例如:splice(2,0,"red","green"),会从当前数组的位置2开始插入字符串"red"和"green"。
替换: 可以向指定位置插入任意数量的项,且同事删除任意数量的项,只需提供3个参数:起始位置、要删除的项数和要插入的任意数量的项。插入的项数不必与删除项数相等。例如:splice (2,1,"red","green") 会删除当前数组位置2的项,然后再从位置2开始插入字符串。
var colors = ["red","green","black"]; var removed = colors.splice(0,1); console.log(colors); //["green","black"] console.log(removed); //["red"] removed = colors.splice(1,0,"yellow","orange"); console.log(colors); //["green","yellow","orange","black"] console.log(removed); //[] removed = colors.splice(1,1,"red","purple"); console.log(colors); //["green","red","purple","orange","black"] console.log(removed); //["yellow"]
8、位置方法indexOf()和lastIndexOf()
相关文章:
js数组操作方法总结(必看篇)
JS数组去重方法总结
相关视频:
js数组和对象-千锋教育JS实战视频教程
以上就是js学习中经常遇到的数组方法,总结很到位的详细内容,更多请关注Gxl网其它相关文章!