- slice 切割数组实现克隆是浅拷贝
let arr = [1,2, {name:1}]
let newarr = arr.slice(0);
console.log(newarr) //[1,2, {name:1}]
newarr[2].name = 666;
console.log(arr[2].name);//666
- JSON实现克隆 深拷贝
let arr = [1,2, {name:1}]
let newarr = JSON.parse( JSON.stringify(arr) )
newarr[2].name = 666;
console.log(arr[2].name) //1
3.Object.assign() 浅拷贝
let arr = [1,2, {name:1}]
let newarr = Object.assign([],arr)
newarr[2].name = 666;
console.log(arr[2].name) //666
- 转换为真数组
let obj = {
0:"1",
1:"2",
length: 2
}
let arr = Array.prototype.slice.call(obj,0)
//也可以写成Array.prototype.slice.call(obj)
console.log(arr)
5. 数组随机排序
let ar = [1,2,3,4,5,6,7,8,9,10]
ar.sort(()=> (Math.random()-0.5))