首页 > 解决方案 > 操作符“&&”在下面的代码片段中详细做了什么?

问题描述

我想知道为什么哈希对象中的属性值不是“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}

标签: javascriptoperators

解决方案


&& 是逻辑与。接下来,array.push返回更新数组的长度,因此将其分配给哈希。但是,你也会得到同样的结果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)

您问题的第二部分 - 为什么它分配 not truebut number,请参见下面的小代码......逻辑 AND 表达式从左到右进行评估,使用以下规则测试可能的“短路”评估:(some falsy expression) && expr

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


推荐阅读