【问题标题】:can anyone tell me how this syntax is called and what it does? [duplicate]谁能告诉我这个语法是如何被调用的以及它是做什么的? [复制]
【发布时间】:2014-07-18 09:56:57
【问题描述】:

我正在阅读 Ionic 的源代码并在这里偶然发现了这部分。

fromTemplateUrl: function(url, options, _) {
  var cb;
  //Deprecated: allow a callback as second parameter. Now we return a promise.
  if (angular.isFunction(options)) {
    cb = options;
    options = _;
  }
  return $ionicTemplateLoader.load(url).then(function(templateString) {
    var modal = createModal(templateString, options || {});
    cb && cb(modal);
    return modal;
  });
}

第 10 行 "cb && cb(modal);" 中的语法是什么,它的作用是什么?

条件 && 让我很困惑

【问题讨论】:

  • 这只是if(cb) cb(modal)的一种更可爱的写作方式。
  • 有道理,这种快捷方式有名字吗?

标签: javascript


【解决方案1】:

谢谢大家,乔恩的回答,更短的方法

if(cb) cb(modal)

结合Assignment with double ampersand "&&"的解释回答我的问题

我会记住这是“short if exists syntax”

【讨论】:

    【解决方案2】:
    undefined && 42 // undefined, the second part wouldn't be evaluated
    'defined' && 42 // 42
    undefined || 42 // 42
    'defined' || 42 // 'defined', the second part wouldn't be evaluated
    

    这样这件事就起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多