数组的函数(一)
push、unshift、pop、shift
let arr1 = ['scdn','csdn.com'];
let arr2 = ['bilibili','bilibili.com'];
arr1.push(...arr2); => ['scdn','csdn.com','bilibili','bilibili.com']
//从后面增加元素,返回数组的length
arr1.unshift('taobao') => ['taobao','scdn','csdn.com','bilibili','bilibili.com']
//从前面增加元素,返回数组的length
arr1.pop(); => ['scdn','csdn.com','bilibili']
//从后面移除一个元素,返回被移除的元素
arr1.shift(); =>['csdn.com','bilibili']]
//从前面移除一个元素,返回被移除的元素
== push、unshift、pop、shift方法否会改变原数组 ==
fill
语法:arr.fill(value[, start[, end]])
Array(5).fill(8); => [8,8,8,8,8]
[1,2,3,4].fill('csdn',1,3) => [1,'csdn','csdn',4]
array.fill(abc,start,end);
//数组的填充,从索引start至end结束
slice
语法:arrayObject.slice(start,end)
let arr = [1,2,3,4,5];
let res = arr.slice(1,2);
console.log(res); => [2]
//arr.slice(start, end); 截取数组,不会改变原数组
splice
语法:arrayObject.splice(index,howmany,item1,.....,itemX)
let arr = [1,2,3,4,5];
let arr1 = arr.splice(0,3);
console.log(arr1); => [1,2,3]
console.log(arr); => [4,5]
//从arr[0]开始截取3个元素,会改变原数组
let arr2 = arr.splice(0,2,'csdn'); => ['csdn','csdn',3,4,5]
//从arr[0]开始将2个元素替换为csdn
let arr3 = arr.splice(1,0,'csdn'); => [1,'csdn',2,3,4,5]
//从arr[1]的位置增加元素'csdn'
copyWithin
语法: array.copyWithin(target, start, end)
用于从数组的指定位置拷贝元素搭配数组的另一个指定位置中
let arr = [1,2,3,4,5,6];
arr,copyWithin(3,1,3) => [1,2,3,2,3,6]
清空数组的多种方式
let arr = [1,2,3,4,5];
arr.length = 0;
arr = []; //最为常用
arr.splice(0,arr.length);
while(arr.pop()){};