今天剛好又碰到這個項目:JS assign 相同值給多個變數
今天又弄懂了一點,發現自己JS基本觀念還是不好,筆記一下。(確認不是逃避Laravel ? XD)
第一直覺是當然是
let a, b, c
//中間有亂七八糟的logic,後面才重新給值
a = 10;
b = 10;
c = 10;
自以為寫漂亮一點就會:
a = b = c = 10;
問題來了,如果要給的值是Array 或是Object呢?
a = b = c = ['This is', 'Global', 'Rachel'];
b[1] = 'Taiwanese';
console.log(a); //['This is', 'Taiwanese', 'Rachel']
console.log(b); //['This is', 'Taiwanese', 'Rachel']
console.log(c); //['This is', 'Taiwanese', 'Rachel']
哇呀全部變了!
這是因為Array, Object, Function 等為可變動的reference types
而原始型別(Primitive values): number, string, boolean, bigint, undefined, symbol, null都是不可變動的,給值時就會被取代。
參閱:
Assign Multiple Variables to the Same Value in JavaScript
Stackoverflow: Assign multiple variables to the same value in Javascript?
如果我們一開始就給多個變數同一值呢?就要小心scope問題:
function test1() {
var a = 1, b = 1, b = 1;
}
function test2() {
var d = e = f = 1;
}
test1();
console.log(b); // undefined
test2();
console.log(e); // 1
改寫:Multiple left-hand assignment with JavaScript