javascript - 带有 javascript 对象的三元表达式

标签 javascript ternary

假设我有以下 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/

相关文章:

javascript - 当变量为空时,JavaScript中的三元运算符

javascript - 如何将这个条件逻辑转换为三元表达式?

javascript - 无法使用 getJSON 从 Flask Rest API 获取 Json

c++ - 具有三元返回和短路的运算符

javascript - 获取从 MVC 中的表中单击的行的 Id

javascript - 在 JavaScript 中生成 JSON 架构

c - 意外结果,Gnu C 中的三元运算符

java - 返回(n > 2)? n = 5 : n = 4; doesn't work?

javascript - 将两个排序数组合并为一个

javascript - 展开时控制台日志中的输出不匹配