Day 15 - Destructuring assignment

Destructuring assignment(解构赋值),这种做法可以从阵列或物件的资料取出值,并对变数赋予这些值。

来举些简单的例子:

  • 阵列解构
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

将 a, b 两变数赋予值为 1, 2,所以 a = 1,b = 2。

const [a, b, ...c] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(c); // [3, 4, 5]

意思为将 a 赋予值为 1,将 b 赋予值为 2,将 c 赋予值为剩下的元素,所以最终 c 为一个阵列 [3,4,5]。

const Friends = ["小美","小胖","小明"];
let [Mary,John,Alex] = Friends;
console.log(Mary); // 小美
console.log(John); // 小胖
console.log(Alex); // 小明
console.log(Friends); // ["小美","小胖","小明"]

从 Friends 这个阵列中取出值,来赋予给 Mary,John 和 Alex,所以 Mary 会是 小美,John 是 小胖,而 Alex 是小明。

  • 物件解构
    过去我们在取得 object 内的资料时,要命名变数并用.方式取得
let person = {
    name:"Amy",
    gender:"female",
    age:24,
    lover:{
        fullName:"John"
    }
}
let name = person.name;
let lover = person.lover.fullName;
console.log(name); // Amy
console.log(lover); // John

使用解构的方式後程序码如下:

let person = {
    name:"Amy",
    gender:"female",
    age:24,
    lover:{
        fullName:"John"
    }
}
let { name, gender, age } = person;
console.log(name); // Amy
console.log(gender); // female
console.log(age); // 24
let { fullName } = person.lover;
console.log(fullName); // John

<<:  听见「多少」下雨的声音

>>:  PHP 规范

Python & SQLALchemy 学习笔记_新增、修改以及删除资料

前一篇文章有提到该如何利用 SQLALchemy 建立一张资料表, 这篇文章主要是纪录该如何利用 S...

Day24 Gin with Cache

前言 我们在并发HTTP Server的时候,经常有对接口内容做缓存的需求。例如:某些热点内容,我们...

NoSQL的查询

NoSQL的查询有两种模式, 分别是Scan与Query Scan会对整个表作扫描. 例如要查询20...

【资料结构】读档相关 12/18更

二维阵列的一维读入法 #include <math.h> #include <st...

除了刷题之外的事 - System Architecture

除了刷题之外的事 刷题是练习解决问题的能力的一种方法,而这里的「问题」主要是指演算法问题。但在实务...