ECMAScript 6 -- 数组的解构赋值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了ECMAScript 6 -- 数组的解构赋值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3001字,纯文字阅读大概需要5分钟。
内容图文
模式匹配:只要等号两边的模式相同,左边的变量就会被赋予对应的值。
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 // []
不完全解构:等号左边的模式,只匹配一部分的等号右边的数组。
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值:
<! DOCTYPE html > < html lang ="en" > < head > < meta charset ="UTF-8" > < title >Document</title></head><body><script>function* fibs() { let a =0; let b =1; while (true) { yield a; [a, b] = [b, a + b]; } } let [first, second, third, fourth, fifth, sixth] = fibs(); alert(sixth); </script></body></html>
对象的解构赋值
解构不仅可以用于数组,还可以用于对象。
<! DOCTYPE html > < html lang ="en" > < head > < meta charset ="UTF-8" > < title >Document</title></head><body><script> let { foo, bar } = {foo: "aaa", bar: "bbb"}; console.log(foo); console.log(bar); </script></body></html>
结果:aaa,bbb
简写:
<! DOCTYPE html > < html lang ="en" > < head > < meta charset ="UTF-8" > < title >Document</title></head><body><script> let obj = { first: ‘hello‘, last: ‘world‘ }; let { first: f, last: l } = obj; console.log(f); console.log(l); </script></body></html>
结果:
hello
world
数组本质是特殊的对象,因此可以对数组进行对象属性的解构。
如下
<! DOCTYPE html > < html lang ="en" > < head > < meta charset ="UTF-8" > < title >Document</title></head><body><script> let arr = [1, 2, 3]; let {0 : first, [arr.length -1] : last} = arr; console.log(first); // 1console.log(last); // 3</script></body></html>
结果为:
1
3
字符串的解构赋值
字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。
<! DOCTYPE html > < html lang ="en" > < head > < meta charset ="UTF-8" > < title >Document</title></head><body><script> const [a, b, c, d, e] =‘hello‘; a // "h"b // "e"c // "l"d // "l"e // "o"console.log(a); console.log(b); console.log(c); console.log(d); console.log(e); </script></body></html>
数值和布尔值的解构赋值
解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
函数参数的解构赋值
<! DOCTYPE html > < html lang ="en" > < head > < meta charset ="UTF-8" > < title >Document</title></head><body><script>function move({x =0, y =0} = {}) { return [x, y]; } console.log(move({x: 3, y: 8})); console.log(move({x: 3})); console.log(move({})); console.log(move()); </script></body></html>
结果:
原文:http://www.cnblogs.com/androidsuperman/p/6889769.html
内容总结
以上是互联网集市为您收集整理的ECMAScript 6 -- 数组的解构赋值全部内容,希望文章能够帮你解决ECMAScript 6 -- 数组的解构赋值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。