学习ES6 变量的解构赋值

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了学习ES6 变量的解构赋值脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

变量的解构赋值

数组解构赋值

let a = 1;
let b = 2;
let c = 3;

ES6允许写成下面这样

let [a,b,c] = [1,2,3];

本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。下面是一些使用嵌套数组进行解构的例子

let [foo, [[bar], baz]] = [1,[[2],3]];
foo //1
bar //2
baz //3

let [ , , third] = ["foo","bar","baz"];
third //"baz"

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
?????????????????????????????????????
    let [x, y, ...z] = ['a']; 
    x // "a"
    y // undefined
    z // []
??????????????????????????????

... 对于三个点号,三点放在形参或者等号左边为rest运算符; 放在实参或者等号右边为sPRead运算符,或者说,放在被赋值一方为rest运算符,放在赋值一方为扩展运算符

eg: reset运算符功能与扩展运算符恰好相反,把逗号隔开的值序列组合成一个数组
    主要用于不定参数,所以ES6开始可以不再使用arguments对象
    VAR bar = function(...args) {
        for(let el of args){ 
            console.LOG(el); 
        }
    }
    bar(1, 2, 3, 4);//1//2//3//4
    bar= function(a, ...args) { 
        console.log(a); 
        console.log(args);
    }
    bar(1, 2, 3, 4); //1//[ 2, 3, 4 ]
    
    扩展运算符:功能是把数组或类数组对象展开成一系列用逗号隔开的值
    var foo = function(a, b, c) { 
        console.log(a); 
        console.log(b); 
        console.log(c);
    }
    var arr = [1, 2, 3];
    //传统写法foo(arr[0], arr[1], arr[2]);
    //使用扩展运算符foo(...arr);//1//2//3
    特殊应用场景:
    //数组深拷贝
    var arr2 =arr;
    var arr3 =[...arr];
    console.log(arr===arr2); //true, 说明arr和arr2指向同一个数组 
    console.log(arr===arr3); //false, 说明arr3和arr指向不同数组
    //把一个数组插入另一个数组字面量
    var arr4 = [...arr, 4, 5, 6];
    console.log(arr4);//[1, 2, 3, 4, 5, 6]
    //字符串转数组
    var str = 'love';
    var arr5 =[...str];
    console.log(arr5);//[ 'l', 'o', 'v', 'e' ]

对于 ?Set ?结构,也可以使用数组的解构赋值。

let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"

解构允许指定默认值

let [foo = true] = []
foo //true

let [x,y = 'b'] = ['a'];// x = 'a', y = 'b'
let [x,y = 'b'] = ['a',undefined]// x = 'a', y = 'b'

注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的。

let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

上面代码中,如果一个数组成员是null,默认值就不会生效,因为null不严格等于undefined

如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。

function f() {
  console.log('aaa');
}
let [x = f()] = [1];

上面代码中,因为x能取到值,所以函数f根本不会执行。上面的代码其实等价于下面的代码。

let x;
if ([1][0] === undefined) {
  x = f();
} else {
  x = [1][0];
}

对象的解构赋值

let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

let{bar,foo} = {foo: "aaa",bar:"bbb"};
foo //"aaa"
bar //"bbb"

let {baz} = {foo: "aaa",bar: "bbb"};
baz //undefined

如果变量名和属性名不一致,必须写成下面这样

var {foo : baz} = {foo : 'aaa',bar: 'bbb'};
baz //"aaa"

let obj = {First: 'hello',last : 'world'};
let {first:f,last:l} = obj;
f //"hello"
l //"world"

这实际上说明,对象的解构赋值是下面形式的简写

let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };

也就是说,对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。

下面是嵌套赋值的例子

var obj = {};
let arr = [];
({foo:obj.prop, bar: arr[0]} = {foo: 123,bar: true});
obj //{prop:123}
arr // [true]

由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构。

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3

字符串的解构赋值

字符串也可以解构赋值,这是因为此时,字符串被转换成了一个类似数组的对象。

const [a, b, c, d, e] = 'hello';
a //h
b //e
c //l
d //l
e //o

类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值

let {length: len} = 'hello';
len //5    

数值和布尔值的解构赋值

解构赋值时,如果等号右边的是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototyPE.toString //true
let {toString: s} = true;
s === Boolean.prototype.toString // true

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefinednull 无法转为对象,所以对他们进行解构赋值,都会报错。

函数参数的解构赋值

**大写的不懂**
function move({x = 0, y = 0} = {}) {
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]

function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]

解构赋值的用途

1.交换变量的值

@H_103_777@let x = 1; let y = 2; [x, y] = [y, x];

2.从函数返回多个值

// 返回一个数组
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

3.函数参数的定义:解构赋值可以方便的将一组参数与变量名对应起来

// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

4.函数参数的默认值

jquery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  croSSDomain = false,
  global = true,
  // ... more config
}) {
  // ... do stuff
};

指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。

5.提取JSON数据:解构赋值对提取JSON对象中的数据,尤其有用

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);// 42, "OK", [867, 5309]

6.遍历Map解构

var map = new Map();
map.set('first','hello'),
map.set('second','world');

for(let[key,value] of map){
    console.log(key + " is " + value);
}
//first is hello
//second id world

7.输入模块的制定方法:加载模块时,往往需要制定输入哪些方法。解构赋值使得语句非常清晰

???????????????????
const { SourceMapConsumer, SourceNode } = require("source-map");
???????????????????

脚本宝典总结

以上是脚本宝典为你收集整理的学习ES6 变量的解构赋值全部内容,希望文章能够帮你解决学习ES6 变量的解构赋值所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。