javascript - 操作符“&&”在下面的代码片段中详细做了什么?
问题描述
我想知道为什么哈希对象中的属性值不是“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
返回更新数组的长度,因此将其分配给哈希。但是,你也会得到同样的结果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 true
but number
,请参见下面的小代码......逻辑 AND 表达式从左到右进行评估,使用以下规则测试可能的“短路”评估:(some falsy expression) && expr
console.log(true && 13);
console.log(false && 99);
推荐阅读
- javascript - 用 2 个日期在 javascript 中对 json 数据进行排序
- sql - 点和多边形之间的 STDistance 始终返回 0,即使它们相距数英里
- python - 在 Python 的 @classmethod 装饰器中使用 setattr 好不好
- selenium - Selenium 请求返回错误 400 - 错误请求
- mysql - Mysql:使用来自不同表/列的值更新 json 列
- elasticsearch - Elasticsearch 最新文章查询一组 id
- memory-management - 主存访问时间包括什么?
- python - 使用 Pywinauto 选择 Combobox 项
- javascript - onkeypress 在反应时不能正常工作吗?
- javascript - 将svg图像下载为PNG