简体   繁体   中英

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

I want to know why the property's value is not "true" in hash object, I assign the property into "true" in the statement " hash.jason = 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}

&& is logical AND. Next, array.push returns length of updated array, so you assign it to hash. But, the same result you'll also get without 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)

Second part of your question - why it's assigning not true but number , see little code below... The logical AND expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some falsy expression) && expr

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM