【问题标题】:What is this ternary expression doing?这个三元表达式在做什么?
【发布时间】:2015-12-01 17:30:24
【问题描述】:

我有一个我正在测试的函数,它接受两个参数定义和元素,并且其中有一个类似于

的三元语句
otherThingName: (_.has(Definition.thing, 'thingName') ? Element[Definition.thing.thingName] : null)

现在Definition.thing.thingName 将存在,但元素没有名为Definition 的属性。

是否在同一设置 otherThingName 时在 Element 上设置了该属性?

【问题讨论】:

  • 不看更多代码就无法判断。
  • 没有。这里的括号表示法用作 getter。如果Element 具有该属性,则返回其值,否则返回undefined 值。没什么特别的。
  • Element 是否有一个名为 Definition 的属性并不重要。方括号表示法表示它正在寻找Element.xyz,其中xyzDefinition.thing.thingName 中包含的值。
  • 这是一个奇怪的错字,请刷新页面。
  • 啊,明白了。更简单

标签: javascript ternary-operator


【解决方案1】:

三元表达式有点像 if/else 的简写,所以首先,它测试语句 (_.has(Definition.thing, 'thingName')

我不使用下划线,但看起来此测试正在检查 Definition.thing 是否具有 thingName 的属性。

如果返回 true,它会将 otherThingName 设置为 Element[Definition.thing.thingName]

否则会将其设置为null

Element[Definition.thing.thingName] 正在查看一个名为 Element 的对象,并使用与 Definition.thing.thingName 的值匹配的键拉回属性。

例如,如果

Definition.thing.thingName == "name",

Element[Definition.thing.thingName] == Element["name"] == Element.name.

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    展开文字会更清楚一点:

    var str;
    
    if (_.has(Definition.thing, 'thingName')) {
        str = Element[Definition.thing.thingName]
    } else {
        str = null;
    }
    
    ...
        otherThingName: str
    

    看起来它正在将某个对象“otherThingName”的成员定义为 Element 为字段 Definition.thing.thingName 设置的任何内容(如果存在),否则为 null。

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 2012-02-13
      • 2020-10-16
      • 2014-07-13
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多