数组方法

2018-05-11  本文已影响0人  巴依老爷_0b46

1. push

push()将新元素追加到一个数组中,并将数组的长度+1。

var color1 = ['red', 'yellow', 'blue'];
color1.push('green');
console.log(color1);//["red", "yellow", "blue", "green"]
console.log(color1.length);//4

2. pop

push()将数组中最后一个元素移除,,并将数组的长度-1。

var color1 = ['red', 'yellow', 'blue','green'];
color1.pop();
console.log(color1);//["red", "yellow", "blue"]
console.log(color1.length);//3

3. shift

shift()将数组中第一个元素移除(前端),,并将数组的长度-1。

var color1 = ['red', 'yellow', 'blue','green'];
color1.shift();
console.log(color1);//[ "yellow", "blue",'green']
console.log(color1.length);//3

4. unshift

unshift()将新元素追加到一个数组的前端,并将数组的长度+1。

var color1 = ['red', 'yellow', 'blue','green'];
color1.unshift('gray');
console.log(color1);//["gray", "red", "yellow", "blue", "green"]
console.log(color1.length);//5

5. join

join()作用是把数组元素(对象调用其toString()方法)使用参数作为连接符连接成一字符串,不会修改原数组内容.

var color1 = ['red', 'yellow', 'blue','green'];
console.log(color1.join('+'));//"red+yellow+blue+green"
console.log(color1.join('和'));//"red和yellow和blue和green"
console.log(color1.join(' '));//"red yellow blue green"
console.log(color1);//["red", "yellow", "blue", "green"]

6. splice

splice() 方法通过删除现有元素和/或添加新元素来更改一个数组的内容。
语法arrayObject.splice(index,howmany,item1,.....,itemX)

splice方法使用deleteCount参数来控制是删除还是添加:
start参数是必须的,表示开始的位置(从0计数),如:index=0从第一个开始;index>= array.length-1表示从最后一个开始。
1、从index位置开始删除[index,end]的元素。
array.splice(start)
2、从index位置开始删除[start,Count]的元素。
array.splice(start, howmany)
3、从index位置开始添加item1, item2, ...元素。
array.splice(index, 0, item1, item2, ...)


var a = [1,2,3,4,5];
a.splice(1,0,9,99,999);
console.log(a.length); //8
console.log(a);//[1, 9, 99, 999, 2, 3, 4, 5]
a.splice(1,3,8,88,888);
console.log(a.length);//8
console.log(a);//[1, 8, 88, 888, 2, 3, 4, 5]

6. sort

sort()对数组的元素进行排序,并返回数组。 sort 排序不一定是稳定的。默认排序顺序是根据字符串Unicode码点。
语法

arr.sort() 
arr.sort(compareFunction)

compareFunction可选。用来指定按某种顺序进行排列的函数。如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序。


var a=[5,4,3,2,1]
a.sort()
console.log(a) //[1, 2, 3, 4, 5]

7. reverse

reverse()方法用于将数组逆序,与之前不同的是它会修改原数组.

var nub = ['one', 'two', 'three'];
nub.reverse();
console.log(nub); //['three', 'two', 'one']

8. concat

concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。
concat 方法并不影响原字符串。

语法

str.concat(string2, string3[, ..., stringN])


var hello = "Hello, ";
console.log(hello.concat("任务20")); //*"Hello, 任务20"
上一篇 下一篇

猜你喜欢

热点阅读