簡體   English   中英

操作符“&&”在下面的代碼片段中詳細做了什么?

[英]what the operator “ &&” do in detail in the following snippet?

我想知道為什么hash object中的屬性值不是“true”,我在語句“hash.jason = true”中將屬性賦值為“true”

var array=[]

var array=[]

 hash.jason = true && array.push('jason')

 hash.tom = true && array.push('tom')

 hash.lucy = true && array.push('lucy')

the output is:

array
(3) ["jason", "tom", "lucy"]

hash
{jason: 1, tom: 2, lucy: 3}

&& 是邏輯與。 接下來, array.push返回更新數組的長度,因此您將其分配給 hash。 但是,如果沒有true && ,你也會得到同樣的結果

 const array = []; const hash = {}; // array.push itself returns length of // updated array, so here you // assign this length to hash hash.jason = true && array.push('jason'); // But will not push to array if false hash.tom = false && array.push('tom'); // Without 'true &&' will do the same hash.lucy = array.push('lucy'); // Log console.log(array) console.log(hash)

你問題的第二部分 - 為什么它分配不是true而是number ,請參見下面的小代碼......邏輯 AND 表達式從左到右進行評估,使用以下規則測試可能的“短路”評估:( (some falsy expression) && expr

 console.log(true && 13); console.log(false && 99);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM