首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript速记如果+速记分配

Javascript速记如果+速记分配
EN

Stack Overflow用户
提问于 2016-03-30 02:37:36
回答 2查看 783关注 0票数 0

我想知道是否有办法将速记与速记+=合并

就像这样:

代码语言:javascript
复制
var value;
$.each(data.events, function(index, element) {
    var otherValue = element.value;
    value = value ? value + otherValue : '';
}

要防止的事

代码语言:javascript
复制
value += otherValue

从添加“未定义”到值未定义时的开头。

较长的版本如下:

代码语言:javascript
复制
var value;
$.each(data.events, function(index, element) {
    var otherValue = element.value;
    if(value){
        value = value + otherValue;
    }

}

我希望这个问题不要(太混乱) :)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-30 03:06:12

编辑:

Geeze,我贴的几乎完全相反,你在你的底部的例子。我本想在这里删除我的问题,但它被接受了。

您可以使用AND &&运算符:

代码语言:javascript
复制
console.log('foo' && 'hello'); // prints hello
console.log(null && 'hello'); // prints null
console.log(undefined && null); // prints undefined
console.log('foo' && null && 'bar'); // prints null


var value;
$.each(data.events, function(index, element) {
    // if value is undefined, null, or empty then it stays the same.
    // otherwise add append the element value
    value = (value && value + element.value);
}

虽然这并不比你的原著更易读

代码语言:javascript
复制
var value;
$.each(data.events, function(index, element) {
    // if value is undefined, null, or empty then it stays the same.
    // otherwise add append the element value
    if(value) value += otherValue;
}

我把原来的答案留在下面,我读了你的问题,看到了你的第一个代码片段,并回答了这个问题。但是你的第二个代码片段做了一些不同的事情,我不确定现在的答案是什么.

您可以使用||操作符返回它看到的第一个未定义的值,因为表达式为true (例如:!!val === true)或操作符序列中的最后一个值(假设您使用了all or语句||)。

代码语言:javascript
复制
console.log(undefined || 'hello'); // prints hello
console.log('' || 'hello'); // prints hello
console.log(undefined || null); // prints null
console.log(undefined || '' || null); // prints null

因此,在您的示例中,使用工作时间较长的JavaScript代码,我们可以将其简化为以下内容

代码语言:javascript
复制
var value;
$.each(data.events, function(index, element) {
    value = (value && value+element.value);
}
票数 1
EN

Stack Overflow用户

发布于 2016-03-30 02:40:40

就像这样:

value = value && value + otherValue || value

另一种可能的办法是:

value && (value += otherValue)

就像如果value是真实的,评估下一个学期的(value += otherValue)

虽然我不会选择这些路径,但我认为我们在编码中需要考虑的问题之一不仅仅是代码有多短,而且还在于可读性。

我还是希望

代码语言:javascript
复制
if(value)
    value += otherValue;

因为它更容易阅读和看到你在那里有一个条件

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36298675

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档