是否有任何方法可以为此示例返回 bool 值而不是操作数之一?
var json = {"test":"asd", "example":"fgh"};
var exists = json.test && json.example;
console.log(exists); // returns 'fgh'
console.log(json.test && json.example); // returns 'fgh'
实现相当于:
var json = {"test":"asd", "example":"fgh"};
var exists= json.hasOwnProperty("test") && json.hasOwnProperty("example");
console.log(exists); // returns true
最佳答案
这是将非 bool 值转换为 bool 值的方法
var json = {"test":"asd", "example": "fgh"};
var exists = !!(json.test && json.example); // converts to boolean
console.log(exists); // returns a boolean value
关于javascript - 返回 bool 值而不是操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43837851/