ES6学习笔记之——数组的解构赋值

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 [x, , y] = [1, 2, 3];
x // 1
y // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

如果解构不成功,变量的值就等于undefined。

2.不完全解构,即等号左边的模式,只匹配一部分的等号右边的数组:

let [x, y] = [1, 2, 3];
x // 1
y // 2

let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

3.如果等号的右边不是数组,将会报错:

// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

4.默认值:

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

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

let [x = 1] = [null];
x // null
let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError: y is not defined

二、对象的解构赋值

let { foo, bar } = { foo: "a", bar: "b" };
foo // "a"
bar // "b"

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

let { bar, foo } = { foo: "a", bar: "b" };
foo // "a"
bar // "b"

let { bas } = { foo: "a", bar: "b" };
baz // undefined

如果变量名与属性名不一致,写成下面这样:
 

let { foo: baz } = { foo: 'a', bar: 'b' };
baz // "a"

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

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

let { foo: baz } = { foo: "a", bar: "b" };
baz // "a"
foo // error: foo is not defined

上面代码中,foo是匹配的模式,baz才是变量。真正被赋值的是变量baz,而不是模式foo。

下面是嵌套赋值的例子:

let obj = {};
let arr = [];

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

obj // {prop:123}
arr // [true]

对象的解构也可以指定默认值:

var {x = 3} = {};
x // 3

var {x, y = 5} = {x: 1};
x // 1
y // 5

var {x: y = 3} = {};
y // 3

var {x: y = 3} = {x: 5};
y // 5

var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"

三、字符串的解构赋值

 

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

四、数值和布尔值的解构赋值

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

五、函数参数的解构赋值

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

六、圆括号问题 

不能使用圆括号的情况:

(1)变量声明语句:

// 全部报错
let [(a)] = [1];

let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};

let { o: ({ p: p }) } = { o: { p: 2 } };

(2)函数参数:

// 报错
function f([(z)]) { return z; }
// 报错
function f([z,(x)]) { return x; }

(3)赋值语句的模式:

// 全部报错
({ p: a }) = { p: 42 };
([a]) = [5];

可以使用圆括号的情况:

可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号。

[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确

七、用途

(1)交换变量的值

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)提取 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]

(5)函数参数的默认值

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

(6)遍历 Map 结构

 

const 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 is world

(7)输入模块的指定方法

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

 

参考资料:ECMAScript 6 入门

作者:阮一峰

更详细资料请点击传送门阅读,ECMAScript 6 入门

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ES6数组解构赋值是一种便捷的语法,可以将数组中的元素分配给变量。通过解构赋值,可以轻松地从数组中提取值并将其赋给变量。这种语法可以简化代码,并使代码更易于理解和维护。 使用数组解构赋值,可以按照特定的顺序将数组中的元素赋值给变量。例如,如果我们有一个包含三个元素的数组[1, 2, 3],我们可以使用解构赋值将每个元素分配给对应的变量。代码示例如下: const arr = [1, 2, 3]; const [a, b, c] = arr; console.log(a, b, c); // 输出1, 2, 3 在上面的代码中,我们定义了一个名为arr的数组,并使用解构赋值数组中的第一个元素赋值给变量a,第二个元素赋值给变量b,第三个元素赋值给变量c。最后,我们将这些变量的值打印出来。 需要注意的是,解构赋值的顺序与数组中元素的顺序有关。换句话说,解构赋值的左边的变量必须与数组中的元素的顺序相对应。如果解构赋值的变量数目少于数组中的元素数目,那么多余的元素将被忽略。如果解构赋值的变量数目多于数组中的元素数目,那么多余的变量将被赋值为undefined。 此外,需要注意的是,解构赋值只能用于具有Iterator接口的数据结构。这意味着,只要数据结构具有Iterator接口,就可以使用数组形式的解构赋值来提取值。 总结来说,ES6数组解构赋值是一种方便的语法,可以将数组中的元素分配给变量。它可以简化代码,提高代码的可读性和可维护性。通过数组解构赋值,可以按照特定的顺序将数组中的元素赋值给变量,并且解构赋值只能用于具有Iterator接口的数据结构。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [ES6数组与对象的解构赋值详解](https://download.csdn.net/download/weixin_38621870/12940725)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [ES6-----数组解构](https://blog.csdn.net/zhouzhou20002000/article/details/128325411)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [ES6 数组解构学习](https://blog.csdn.net/QY_99/article/details/126279215)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值