以逗号为分隔符:str.split(',')
- const str = '1,2,3,4,5';
- console.log(str.split(',')); // ["1", "2", "3", "4", "5"]
方法:arr.toString()
- const arr = ["1", "2", "3", "4", "5"];
- console.log(arr.toString()); // 1,2,3,4,5
方法:arr.map(String)
- const arr = [1, 2, 3, 4, 5, 6];
- console.log(arr.map(String)); // ["1", "2", "3", "4", "5", "6"]
方法:arr.map(Number)
- const arr = ['1', '2', '3', '4', '5', '6'];
- console.log(arr.map(Number)); // [1, 2, 3, 4, 5, 6]
方法:num.toString().split('')
- const num = 123456;
- console.log(num.toString().split('')); // ["1", "2", "3", "4", "5", "6"]
方法:arr.shift()
返回值:被删除的元素(即数组原来的第一个元素)。
如果数组是空的,那么 shift() 方法将不进行任何操作,返回 undefined 值。
该方法不创建新数组,而是直接修改原有的数组。所以该方法会改变数组的长度。
- const arr = [1, 2, 3, 4, 5, 6];
- arr.shift();
- console.log(arr); // [2, 3, 4, 5, 6]
方法:arr.pop()
返回值:被删除的元素(即数组原来的最后一个元素)。
如果数组是空的,那么 pop() 方法将不进行任何操作,返回 undefined 值。
该方法不创建新数组,而是直接修改原有的数组。所以该方法会改变数组的长度。
- const arr = [1, 2, 3, 4, 5, 6];
- arr.pop();
- console.log(arr); // [1, 2, 3, 4, 5]
方法一:arr.push(value1, value2)
- const arr = [1, 2, 3, 4];
- arr.push(6, 7);
- console.log(arr); // [1, 2, 3, 4, 6, 7]
方法二:使用扩展运算符(…)
- const arr = [1, 2, 3, 4, 5];
- const newArr = [...arr, 6, 7];
- console.log(newArr); // [1, 2, 3, 4, 5, 6, 7]
方法一:arr.unshift(value1, value2)
- const arr = [1, 2, 3, 4];
- arr.unshift(6, 7);
- console.log(arr); // [6, 7, 1, 2, 3, 4]
方法二:使用扩展运算符(…)
- const arr = [1, 2, 3, 4, 5];
- const newArr = [6, 7, ...arr];
- console.log(newArr); // [6, 7, 1, 2, 3, 4, 5]
方法三:newArr.concat(arr)
- const arr = [1, 2, 3, 4, 5];
- const newArr = [6, 7];
- console.log(newArr.concat(arr)); // [6, 7, 1, 2, 3, 4, 5]
在数组的第二位中插入元素:arr.splice(2, 0, value1, value2)
array.splice(index, 0, insertValue),返回值为空数组,array 值为最终结果值
index:第一个参数(插入位置)
0:第二个参数(固定为0[需要删除的个数])
insertValue:第三个参数(插入的项[可多个,用逗号隔开])
- const arr = [1, 2, 3, 4];
- arr.splice(2, 0, 6, 7);
- console.log(arr); // [1, 2, 6, 7, 3, 4]
push 将新数组添加到原数组的末尾,会改变原数组
- const tempArr = [1, 2, 3, 4];
- tempArr.push(5);
- console.log(tempArr); // [1, 2, 3, 4, 5]
把追加的数组作为元素的某一项添加到原数组的末尾
- const tempArr = [1, 2, 3, 4];
- tempArr.push([6, 7]);
- console.log(tempArr); // [1, 2, 3, 4, [6, 7]]
push.apply 将后一个数组的值依次 push 进前一个数组里,使前一个数组发生改变,并且只能两个数组之间发生合并,会改变原数组
- const arr1 = [1, 2, 3, 4];
- const arr2 = [4, 5, 6, 7];
- arr1.push.apply(arr1, arr2);
- console.log(arr1); // [1, 2, 3, 4, 4, 5, 6, 7]
concat 合并数组之后,返回值才是新数组,并且可以合并两个及其以上的数组,不改变原数组
- const tempArr = [1, 2, 3, 4];
- const newArr = tempArr.concat([7, 8]);
- console.log(newArr); // [1, 2, 3, 4, 7, 8]
总结:push 和 push.apply 会改变原数组;concat 不改变原数组,返回值才是新数组