我知道我可以测试一个JavaScript变量,然后定义它,如果它是未定义的,但有没有某种方式说
var setVariable = localStorage.getItem('value') || 0;
这似乎是一种更清晰的方式,我很确定我在其他语言中见过这种情况。
我知道我可以测试一个JavaScript变量,然后定义它,如果它是未定义的,但有没有某种方式说
var setVariable = localStorage.getItem('value') || 0;
这似乎是一种更清晰的方式,我很确定我在其他语言中见过这种情况。
当前回答
在我们的日子里,你实际上可以用JS来做你的方法:
// Your variable is null
// or '', 0, false, undefined
let x = null;
// Set default value
x = x || 'default value';
console.log(x); // default value
所以你的例子是有效的:
const setVariable = localStorage.getItem('value') || 0;
其他回答
2018年ES6的答案是:
return Object.is(x, undefined) ? y : x;
如果变量x未定义,返回变量y…否则,如果定义了变量x,则返回变量x。
今天也遇到了这种情况,我不想让几个值的0被覆盖。我们有一个文件,其中包含一些用于此类场景的通用实用程序方法。下面是我为处理这种情况而添加的内容。
function getIfNotSet(value, newValue, overwriteNull, overwriteZero) {
if (typeof (value) === 'undefined') {
return newValue;
} else if (value === null && overwriteNull === true) {
return newValue;
} else if (value === 0 && overwriteZero === true) {
return newValue;
} else {
return value;
}
}
然后,如果我想只设置为未定义的值或也覆盖null或0值,可以调用最后两个参数作为可选。这里有一个调用它的例子,如果ID是undefined或null,它会将ID设置为-1,但不会覆盖0值。
data.ID = Util.getIfNotSet(data.ID, -1, true);
var setVariable = (typeof localStorage getItem(’value’)! = =’undefined’&& localStorage getItem(’value’))| | 0;
我需要在几个地方“设置一个未定义的变量”。我用@Alnitak answer创建了一个函数。希望它能帮助到某些人。
function setDefaultVal(value, defaultValue){
return (value === undefined) ? defaultValue : value;
}
用法:
hasPoints = setDefaultVal(this.hasPoints, true);
ES2020回答
使用Nullish Coalescing Operator,如果value为空或未定义,则可以设置默认值。
const setVariable = localStorage.getItem('value') ?? 0;
但是,您应该注意,空合并运算符不会为其他类型的假值(如0和")返回默认值。
但是,一定要注意浏览器的支持。您可能需要使用像Babel这样的JavaScript编译器将其转换为向后兼容的内容。如果你正在使用Node.js,它从版本14开始就被支持了。