我想知道是否有办法将速记与速记+=合并
就像这样:
var value;
$.each(data.events, function(index, element) {
var otherValue = element.value;
value = value ? value + otherValue : '';
}要防止的事
value += otherValue从添加“未定义”到值未定义时的开头。
较长的版本如下:
var value;
$.each(data.events, function(index, element) {
var otherValue = element.value;
if(value){
value = value + otherValue;
}
}我希望这个问题不要(太混乱) :)
发布于 2016-03-30 03:06:12
编辑:
Geeze,我贴的几乎完全相反,你在你的底部的例子。我本想在这里删除我的问题,但它被接受了。
您可以使用AND &&运算符:
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);
}虽然这并不比你的原著更易读
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语句||)。
console.log(undefined || 'hello'); // prints hello
console.log('' || 'hello'); // prints hello
console.log(undefined || null); // prints null
console.log(undefined || '' || null); // prints null因此,在您的示例中,使用工作时间较长的JavaScript代码,我们可以将其简化为以下内容
var value;
$.each(data.events, function(index, element) {
value = (value && value+element.value);
}发布于 2016-03-30 02:40:40
就像这样:
value = value && value + otherValue || value
另一种可能的办法是:
value && (value += otherValue)
就像如果value是真实的,评估下一个学期的(value += otherValue)
虽然我不会选择这些路径,但我认为我们在编码中需要考虑的问题之一不仅仅是代码有多短,而且还在于可读性。
我还是希望
if(value)
value += otherValue;因为它更容易阅读和看到你在那里有一个条件
https://stackoverflow.com/questions/36298675
复制相似问题