当前位置:网站首页>深入JS中几种数据类型的解构赋值细节
深入JS中几种数据类型的解构赋值细节
2022-07-04 14:29:00 【InfoQ】
解构赋值
- 解构:可以在数组或对象中的值分离出来
- 赋值:将解构出来的数据对变量进行赋值
var a = 1;
var b = 2;
let [a,b] = [1,2] // 等价于上述
数组解构
嵌套解构
let [a,[b],c] = [1,[1,2],3]
console.log(a,b,c) // 1 1 3
扩展运算符解构
...let [a,...b] = [1,2,3,4]
console.log(a,b)
// a = 1 b = [2,3,4]
不完全解构
let [, , a] = [1,2,3]
console.log(a) // 3
不成功的解构
let [a] = 1
console.log(a) // TypeError: 1 is not iterable
blet [a,b] = [1]
console.log(a,b) // 1 undefined
关于
interator
1 is not iterableinteratorinteratorundefinednullNaNinteratorinteratorinterator带有默认值的解构赋值
let [a,b=2] = [1]
console.log(a,b) // 1 2
let [c = 1] = [undefined]
console.log(c) // 1
关于
undefined
的问题
NaNnulllet [c = 1] = [NaN]
console.log(c) // NaN
let [c = 1] = [null]
console.log(c) // null
===NaNnullundefined对象解构
与数组解构的不同
let {name} = {name:"猪痞恶霸"}
console.log(name) // 猪痞恶霸
变量名与属性名不一致
:let {name:difname} = {name:"猪痞恶霸"}
console.log(difname) // 猪痞恶霸
name多层嵌套对象的解构赋值
let people = {
name:"猪痞恶霸",
like:{
community:"juejin",
code:"js"
}
}
let {name,like:{code}} = people
console.log(name,code) // 猪痞恶霸 js
codelikelikecode模式问题
likelike is not defined字符串解构
let str = "猪痞恶霸"
let {1:first} = str
console.log(first) // 痞
let str = "猪痞恶霸"
let [a] = str
console.log(a) // 猪
let str = "猪痞恶霸"
let {length} = str
console.log(length) // 4
数值与布尔值解构
let { toFixed:a} = 123
console.log(a) // toFixed() { [native code] }
toFixed利用原型链判断
toFixedconsole.log(a === Number.prototype.toFixed) // true
函数参数解构
function add([x,y]) {
return x+y
}
add([1,2]) // 3
let arr = [[1,2],[2,3]]
arr.map((item) => item[0]+item[1])
let arr = [[1,2],[2,3]]
arr.map(([a,b]) => a+b)
解构的歧义
===参考文献
- ES6标准入门第三版
边栏推荐
- Huawei cloud database DDS products are deeply enabled
- 【读书会第十三期】视频文件的编码格式
- 這幾年爆火的智能物聯網(AIoT),到底前景如何?
- PXE网络
- Introduction of text mining tools [easy to understand]
- LNX efficient search engine, fastdeploy reasoning deployment toolbox, AI frontier paper | showmeai information daily # 07.04
- MySQL learning notes - data type (numeric type)
- Force button brush question 01 (reverse linked list + sliding window +lru cache mechanism)
- CentOS 6.3 下 PHP编译安装JSON模块报错解决
- 中国主要城市人均存款出炉,你达标了吗?
猜你喜欢
随机推荐
十六进制
Align left and right!
直播预告 | PostgreSQL 内核解读系列第二讲:PostgreSQL 体系结构
unity update 协程_Unity 协程的原理
Ffmpeg Visual Studio development (IV): audio decoding
Enter the width!
Preliminary exploration of flask: WSGI
CentOS 6.3 下 PHP编译安装JSON模块报错解决
Openresty redirection
They are all talking about Devops. Do you really understand it?
How to build a technical team that will bring down the company?
Memory management summary
PXE网络
Quelles sont les perspectives de l'Internet intelligent des objets (aiot) qui a explosé ces dernières années?
Flutter reports an error no mediaquery widget ancestor found
MySQL learning notes - data type (numeric type)
怎么判断外盘期货平台正规,资金安全?
基于MAX31865的温度控制系统
Is BigDecimal safe to calculate the amount? Look at these five pits~~
What are the concepts of union, intersection, difference and complement?








