(一看就懂)JavaScript ES6入门——扩展运算符与解构赋值
需要解构赋值的数组是有顺序排列的,变量取值由顺序和长度决定
````js
let [a,b,c] = [1,2,3]
console.log(a,b,c); // 1 2 3
````
如果长度不一样
````js
let [a,b] = [1,2,3]
console.log(a,b); // 1 2
let [c,d,e] = [1,2]
console.log(c,b,e); //1 2 undefined
````
如果想不确定右边的值或者想用两个变量接收则可以用扩展运算符
````js
// 正确写法
let [a,b,...c] = [1,2,3,4,5,6,7]
console.log(a,b,c); // 1 2 [3, 4, 5, 6, 7]
// 但是可以
let arr = [1,2,3]
let b = [0,...arr,4,5,6]
console.log(b); //[0, 1, 2, 3, 4, 5, 6]
````
使用扩展运算符解构赋值的时只能将其放到末尾不可以放到中间
````js
let [a,...b,c] = [1,2,3,4,5,6,7]
console.log(a,b,c); //Uncaught SyntaxError: Rest element must be last element
````
当...用在数组时,他会把这个变量展开 成为各个独立的值
es6中使用扩展运算符传参
````js
function fn(a,b,c){
console.log(a,b,c);
}
fn(...[1,2,3]) // 123
//或者
let arr = [1,2,3]
function fn(a,b,c){
console.log(a,b,c);
}
fn(...arr) // 123
````
而在es5中想要完成该方法则需要使用apply
````js
// 不使用apply时
let arr = [1,2,3]
function fn(a,b,c){
console.log(a,b,c);
}
fn(arr) // [1, 2, 3] undefined undefined
// 使用apply时
let arr = [1,2,3]
function fn(a,b,c){
console.log(a,b,c);
}
fn.apply(this,arr) // 123
````
可以使用扩展运算符替换arguments,arguments实际上并不是一个真正的数组,他其实是带有一个length属性的Object对象
````js
function fn(){
console.log(arguments instanceof Array);
console.log(arguments instanceof Object);
}
fn() // false true
````
因为arguments是一个伪数组,所以并不能使用数组方法
````js
function fn(){
arguments.push(5)
}
fn() // Uncaught TypeError: arguments.push is not a function
function fn(){
arguments.pop(5)
}
fn() // Uncaught TypeError: arguments.pop is not a function
````
如果想在es5中将arguments转成真正的数组则需要使用Array.prototype.slice.call()方法
````js
function fn(){
var arg = Array.prototype.slice.call(arguments)
console.log(arg instanceof Array);
arg.push(5)
console.log(arg);
}
fn() // true [5]
````
而在es6出来后 使用扩展运算符则可以将arguments快速的直接成为一个真实的数组
````js
function fn(...arg){
console.log(arg instanceof Array);
arg.push(5)
console.log(arg);
}
fn() // true [5]
````
注意:**扩展运算符对于基本数据为深拷贝而对于引用数据类型的话则为浅拷贝**
````js
let obj = {a:1,b:2,c:[1,2]}
let obj1 ={...obj}
console.log(obj); //{a: 1, b: 2, c: Array(2)}
console.log(obj1);//{a: 1, b: 2, c: Array(2)}
console.log(obj.a == obj1.a); //true
console.log(obj.c == obj1.c); //true
console.log(obj.c[0] == obj1.c[0]); //true
console.log(obj == obj1); //false
let arr = [1,2];
let arr1 = [...arr];
console.log(arr); //[1,2]
console.log(arr1);//[1,2]
console.log(arr[0]==arr1[0]);//true
console.log(arr==arr1);//false
````
浙公网安备 33010602011771号