[英]Javascript return statement error
This is my original code it is a cache using jquery deferreds/promises 这是我的原始代码,它是使用jquery延迟/承诺的缓存
var templateCache = {};
var retrieve = function (templateURL) {
if (!templateCache[templateURL]) {
templateCache[templateURL] = $.get(templateURL);
}
return templateCache[templateURL];
};
I wanted to try to change it to a one liner so i made 我想尝试将其更改为一个衬板,所以我做了
var templateCache = {};
var retrieve = function( templateURL ){
return templateCache[ templateURL ] || templateCache[ templateURL ] = $.get( templateURL );
}
But I keep getting an error that the left hand side of the return statement is invalid 但我不断收到一个错误,指出return语句的左侧无效
在作业周围添加一些括号
return templateCache[ templateURL ] || (templateCache[ templateURL ] = $.get( templateURL ));
||
has a higher precedence than =
. 的优先级比
=
。
Your code is being parsed as (a || b) = c
, which doesn't make any sense. 您的代码被解析为
(a || b) = c
,这没有任何意义。
You need to add parentheses to force the assignment to happen first: 您需要添加括号以强制首先执行分配:
a || (b = c)
here is another way to write it using a ternary operator. 这是使用三元运算符编写它的另一种方法。
var retrieve = function( templateURL ){
return templateCache[ templateURL ] ? templateCache[ templateURL ] : templateCache[ templateURL ] = $.get( templateURL );
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.