假设我有以下 javascript 对象:
var __error__ = {0: 'ok'}
如果键不在 obj 中,我想返回一个空字符串,否则返回一条错误消息。例如:
var value = __error__[col_num] ? "The value cannot be converted" : ""
如何使用三元表达式正确完成此操作?我需要执行 __error__[col_num] == undefined
吗?或者上面的表达式本身计算结果为 false
吗?
最佳答案
如果您只想检查它们的键是否存在于对象中,而不是值的 troothy 为 false
,您应该使用 in
operator
var value = col_num in __error__ ? "The value cannot be converted" : ""
您还可以使用Object.hasOwnProperty
仅当对象具有该属性时才返回 true(如果该属性被继承,则返回 false)。
这里有几个例子来说明差异
var parent = {
foo: undefined
};
var child = Object.create(parent);
console.log("foo" in parent); // parent has the "foo" property
console.log("foo" in child); // child has the "foo" property
console.log(parent.hasOwnProperty("foo")); // parent has the "foo" property
console.log(child.hasOwnProperty("foo")); // child has the "foo" property but it belonds to parent
console.log(child.foo !== undefined); // the foo property of child is undefined
console.log(!!child.foo); // the troothy of undefined is false
console.log(parent.foo !== undefined); // the foo property of parent is undefined
console.log(!!parent.foo); // the troothy of undefined is false
关于javascript - 带有 javascript 对象的三元表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663633/