增删系列方法:
push(元素1,元素2,…,元素n)
功能:往源数组的末端添加元素。
返回值:添加元素后,源数组的长度。
示例:
var a = [1]
a.push(2,3,4)
console.log(a) //(4) [1, 2, 3, 4]
unshift(元素1,元素2,…,元素n)
功能:往源数组从首端添加元素。
返回值:添加元素后,源数组的长度。
示例:
var a = [1]
a.unshift(2,3,4)
console.log(a) //(4) [2, 3, 4, 1]
pop()
功能:把源数组最后一个元素删除。
返回值:被删除的元素。若源数组为空,返回undefined。
示例:
var a = [1,2,3,4]
a.pop() //4
console.log(a) //(3) [1, 2, 3]
var b = []
b.pop() //undefined
console.log(b) //[]
shift()
功能:从源数组首位删除元素。
返回值:被删除的元素。若源数组为空,返回undefined。
示例:
var a = [1,2,3,4]
a.shift() //1
console.log(a) //(3) [2, 3, 4]
var b = []
b.shift() //undefined
console.log(b) //[]
concat(数组1,数组2,…,数组n[非必填])
功能:拼接数组。
返回值:拼接后的数组。
示例:
var a = [0,1,2],
b = [3,4,5],
c = [6,7,8];
a.concat() //(3) [0, 1, 2]
a.concat(b,c) //(9) [0, 1, 2, 3, 4, 5, 6, 7, 8]
console.log(a) //(3) [0, 1, 2]
console.log(b) //(3) [3, 4, 5]
console.log(c) //(3) [6, 7, 8]
splice(开始索引[必填],删除长度[必填],删除处添加的元素[选填])
功能:从源数组任意位置删除元素,并能在删除处添加元素。
返回值:从源数组删除的元素。
示例:
var a = [1,2,3,4],
b = [];
a.splice(1,2,2,3) //(2) [2, 3]
console.log(a) //(4) [1, 2, 3, 4]
a.splice(1,2) //(2) [2, 3]
console.log(a) //(2) [1, 4]
b.splice(1,2,2,3) //[]
console.log(b) //(2) [2, 3]
排序系列方法:
reverse()
功能:把源数组元素倒序。
返回值:倒序后的数组。
示例:
var a = [1,3,5,2,4,6]
a.reverse() //(6) [6, 4, 2, 5, 3, 1]
console.log(a) //(6) [6, 4, 2, 5, 3, 1]
sort(函数[非必填])
功能:没有填参数的时候,默认按ASC码升序;填入参数后按照参数返回值规则处理排序。
返回值:排序后的数组。
示例:
var a = [1,45,23,12,11,4,6]
// 默认按ASC码排序
a.sort() //(7) [1, 11, 12, 23, 4, 45, 6]
// 升序
a.sort(function(now,next){
return now - next
})
//(7) [1, 4, 6, 11, 12, 23, 45]
// 降序
a.sort(function(now,next){
return next - now
})
//(7) [45, 23, 12, 11, 6, 4, 1]
// 乱序
a.sort(function(now,next){
return Math.random() - Math.random()
})
// (7) [12, 11, 45, 6, 23, 4, 1]
说明:sort()方法的参数必须是一个函数,且函数有两个形参案例用(now,Next代替),执行方法的时候,程序会从数组首位,依次取出两位元素传入函数的两个形参,当函数返回值为正数的时候,now被放到next后面,当返回值为负数或为0的时候,位置不变。
数组与字符串相互转换系列方法
数组变字符串
toString()
功能:把数组元素依次用“,”拼接成字符串。
返回值:拼接后的字符串。
示例:
var a = [1,45,23,12,11,4,6]
a.toString() //"1,45,23,12,11,4,6"
console.log(a) //(7) [1, 45, 23, 12, 11, 4, 6]
join(字符[非必填])
功能:按照传入的字符,依次拼接数组元素,不填参数的时候,默认使用“,”拼接。
返回值:拼接后的字符串。
示例:
var a = [1,45,23,12,11,4,6]
a.join() //"1,45,23,12,11,4,6"
a.join('|') //"1|45|23|12|11|4|6"
console.log(a) //(7) [1, 45, 23, 12, 11, 4, 6]
字符串变数组
split(字符[非必填])
功能:把字符串按照填入的字符进行分割字符串。
返回值:分割后生成的数组。
var a = "1,45,23,12,11,4,6",
b = "12345678";
a.split(',') //(7) ["1", "45", "23", "12", "11", "4", "6"]
console.log(a) //"1,45,23,12,11,4,6"
b.split() //["12345678"]
console.log(b) //"12345678"