【问题标题】:Javascript return statement errorJavascript返回语句错误
【发布时间】:2013-10-06 10:36:12
【问题描述】:

这是我的原始代码,它是一个使用 jquery deferreds/promises 的缓存

var templateCache = {};

var retrieve = function (templateURL) {
    if (!templateCache[templateURL]) {
        templateCache[templateURL] = $.get(templateURL);
    }
    return templateCache[templateURL];
};

我想试着把它改成一个衬里,所以我做了

var templateCache = {};
var retrieve = function( templateURL ){
  return templateCache[ templateURL ] || templateCache[ templateURL ] = $.get( templateURL );
}

但我不断收到返回语句左侧无效的错误

【问题讨论】:

    标签: javascript jquery caching return


    【解决方案1】:

    在作业周围添加一些括号

    return templateCache[ templateURL ] || (templateCache[ templateURL ] = $.get( templateURL ));

    【讨论】:

      【解决方案2】:

      || 的优先级高于=

      您的代码被解析为(a || b) = c,这没有任何意义。

      您需要添加括号来强制赋值首先发生:

      a || (b = c)
      

      【讨论】:

        【解决方案3】:

        这是使用三元运算符的另一种编写方式。

        var retrieve = function( templateURL ){
            return templateCache[ templateURL ] ? templateCache[ templateURL ] : templateCache[ templateURL ] = $.get( templateURL );
        };
        

        【讨论】:

          猜你喜欢
          • 2012-05-06
          • 2015-04-13
          • 1970-01-01
          • 1970-01-01
          • 2013-11-26
          • 2013-04-27
          • 2011-11-01
          • 2012-07-07
          • 1970-01-01
          相关资源
          最近更新 更多