【数组】的操作
增
- push()
- 插入后数组长度 = 数组.push(元素);
- 返回数组长度;插入一个元素到数组最后面(改变原数组)
- unshift()
- 插入后数组长度 = 数组.unshift(元素);
- 返回数组长度;插入一个元素到数组最前面(改变原数组)
1
2
3
4
5
6
7
8var arr = [ 1, 2, 3, 4];
var newArrLen1 = arr.push(3);
console.log(newArrLen1); // => 5
console.log(arr); // => [ 1, 2, 3, 4, 3]
var newArrLen2 = arr.unshift(5);
console.log(newArrLen2); // => 6
console.log(arr); // => [5, 1, 2, 3, 4, 3]
删
- pop()
- 删除元素 = 数组.pop();
- 返回被删除的元素;删除数组最后一个元素(改变原数组)
- shift()
- 删除元素 = 数组.shift();
- 返回被删除的元素;删除数组第一个元素(改变原数组)
1
2
3
4
5
6
7
8var arr = [1, 2, 3, 4, 5];
var char1 = arr.pop();
console.log(char1); // => 5
console.log(arr); // => [1, 2, 3, 4]
var char2 = arr.shift();
console.log(char2); // => 1
console.log(arr); // => [2, 3, 4]
连
- concat()
- 连接后的新数组 = 数组1.concat(数组2);
- 返回一个新数组;将数组2添加到数组1后面(原数组不变)
1
2
3
4
5
6var arr1 = [1, 2, 3];
var arr2 = [6, 7, 8];
var newArr = arr1.concat(arr2);
console.log(arr1); // => [1, 2, 3]
console.log(arr2); // => [6, 7, 8]
console.log(newArr); // => [1, 2, 3, 6, 7, 8]
换
join()
- 字符串 = 数组.join(分隔符);
- 返回一个由分隔符分隔开的字符串;(不改变原数组)
split()
- 数组 = 字符串.split(分隔符);
- 返回一个数组(不改变原字符串)
1
2
3
4
5
6
7
8
9
10
11var arr = [1, 2, 3, 4, 5];
var str = arr.join('-');
console.log(arr); // => [1, 2, 3, 4, 5]
console.log(str); // => 1-2-3-4-5
var arr1 = str.split('-');
console.log(arr1); // => ["1", "2", "3", "4", "5"]
var arr2 = str.split();
console.log(arr2); // => ["1-2-3-4-5"]
var arr3 = str.split('');
console.log(arr3); // => ["1", "-", "2", "-", "3", "-", "4", "-", "5"]
查
- length
- 数组长度 = 数组.length;
- 输出数组的长度
1
2
3
4var arr = [1, 2, 3, 4, 5];
var arrLen = arr.length;
console.log(arr); // => [1, 2, 3, 4, 5]
console.log(arrLen); // => 5
改
reverse()
- 数组.reverse();
- 降序排列 (改变原数组)
sort()
- 数组.sort();
- 升序排列 (改变原数组)
- sort() 会调用每个数组项的toString转型方法,然后再比较转换后的字符串
1
2
3
4
5
6
7
8
9var arr1 = [1, 9, 3, 10, 50];
var newArr1 = arr1.reverse();
console.log(arr1); // => [50, 10, 3, 9, 1]
console.log(newArr1); // => [50, 10, 3, 9, 1]
var arr2 = [1, 9, 3, 10, 50];
var newArr2 = arr2.sort();
console.log(arr2); // => [1, 10, 3, 50, 9]
console.log(newArr2); // => [1, 10, 3, 50, 9]