(编辑:jimmy 日期: 2024/12/24 浏览:2)
数组的增删改查
数组的插入
push()尾部插入
var arr2 = [1, 2, 3] arr2.push(4, 5, 6) console.log(arr2) //[1,2,3,4,5,6]
unshift()头部插入
var arr3 = [1, 2, 3] arr3.unshift(4, 5, 6) console.log(arr3) //[4, 5, 6, 1, 2, 3]
splcie 在任意位置内插入,或删除
var arr4 = [1, 2, 3] arr4.splice(1, 1, 888, 999) console.log(arr4) //索引1开始,删除1个元素,然后增加888,999
var arr5 = [1, 2, 3] arr5.splice(1, 0, 888, 999) console.log(arr5) //索引1开始,删除0个元素,然后在索引1前增加888,999
var arr6 = [1, 2, 3] arr6.splice(1, 1) console.log(arr6) //索引1开始,删除1个元素
数组的删除
pop()删除数组的最后一项
var arr7 = [1, 2, 3] arr7.pop() console.log(arr7)
shift() 删除数组的的第一项,返回的是删除的那一项,原有数组改变
var arr8 = [1, 2, 3] arr8.shift() console.log(arr8)
数组的查询
查询用indexOf() ,若存在返回索引值,不存在返回-1
var arr9 = [4, 5, 6, 's'] console.log(arr9.indexOf('s')) //3
其他
数组自定义连接符号 join()
var arr10 = [4, 5, 6, 's'] console.log(arr10.join("-")) //4-5-6-s
数组合并concat()
- var arr11 = [1, 2, 3] var arr11 = arr11.concat(7, 8, 9) console.log(arr11) //7,8,9合并到arr11 var arr12 = [4, 5, 6] var arr13 = [7, 8, 9] console.log(arr12.concat(arr13)) //arr13合并到arr12
数组的排列和排序
reverse() 把数组倒序
var arr14 = [1, 2, 3] console.log(arr14.reverse()) //[3, 2, 1]
sort 可以实现由大到小或者由小到大的排序,但是sort只能排序十以内的数字
var arr15 = [8, 6, 2, 4, 3, 1, 7, 5] console.log(arr15.sort()) //[1, 2, 3, 4, 5, 6, 7, 8]
任意数从小到大排序
var arr = [1, 2, 3, 81, 95, 3]; a = arr.sort(function(a, b) { return (a - b); }); console.log(a); ary.sort(function(a, b) { return (a - b); })
总结