2016-01-13 69 views
-5

我在看這個Javascript類:||的用途是什麼? []操作

'use strict'; 
class Account { 
    constructor(a, b, c) { 
    this.a = a 
    this.b = b || [] 
    this.c = c || [] 
    } 
} 

什麼是b || []說什麼?

+0

這是從哪裏來的? – Lasoloz

+0

如果是b可以被評估爲false,它會返回[],否則返回b – CoderPi

+0

http://stackoverflow.com/questions/4576867/javascript-or-operator-with-a-undefinded-variable – epascarello

回答

1

||運算符返回它看到的第一個真y值。許多人會將此用作設置變量默認值的快捷方式,因爲undefined爲false-y。這樣做的問題是默認也將用於null,false,0,NaN和空字符串(所有這些可能實際上也可能不實際是有效值)。

在這種情況下,如果bcundefined(或任何其它假Y值),和this.bthis.c將被設置爲[]

+0

null'和''''-.- – CoderPi

+0

@CodeiSir' - 我添加了'null'並且已經提到了空字符串。 –