Javascript 字符串中的javascript空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10045805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript null value in string
提问by Nate Pet
In javascript I have the following:
在javascript中,我有以下内容:
var inf = id + '|' + city ;
if id or city are null then inf will be null.
如果 id 或 city 为空,则 inf 将为空。
Is there any slick way of saying if id or city are null make then blank.
如果 id 或 city 为空,则是否有任何巧妙的说法,然后为空。
I know in c# you can do the following:
我知道在 C# 中,您可以执行以下操作:
var inf = (id ?? "") + (city ?? "");
Any similar method in javascript?
javascript中有没有类似的方法?
采纳答案by Philipp
var inf = (id == null ? '' : id) + '|' + (city == null ? '' : city)
回答by psyho
How about:
怎么样:
var inf = [id, city].join('|');
EDIT: You can remove the "blank" parts before joining, so that if only one of id and city is null, inf will just contain that part and if both are null inf will be empty.
编辑:您可以在加入之前删除“空白”部分,这样如果 id 和 city 中只有一个为空,则 inf 将只包含该部分,如果两者都为空,则 inf 将为空。
var inf = _([id, city]).compact().join('|'); // underscore.js
var inf = [id, city].compact().join('|'); // sugar.js
var inf = [id, city].filter(function(str) { return str; }).join('|'); // without helpers
回答by Elliot Bonneville
Total long shot, but try this:
总远射,但试试这个:
var inf = (id || "") + "|" + (city || "");
回答by xdazz
var inf = (id && city) ? (id+"|"+city) : "";
回答by KooiInc
Equivalent to c# var inf = (id ?? "") + (city ?? "");
(if id
and city
are nullable) is
等价于 c# var inf = (id ?? "") + (city ?? "");
(如果id
并且city
可以为空)是
var inf = (id || '') + (city || '');
This is referred to as 'Short-Circuit Evaluation'. Nullability is not an issue in javascript (in js all variables are nullable), but id
and city
have to be assigned (but do not need a value, as in var id, city
).
这被称为“短路评估”。空性是不是在JavaScript的问题(JS中的所有变量都为空的),但id
并city
必须分配(但并不需要一个值,如var id, city
)。
回答by ouday khaled
if (id != ""){
inf = id;
if (city != ""){ inf += " | " + city ;}
}
else
inf= city;
回答by Steve Johnson
function nullToStr(str) {
return !str || 0 === str.length ? '' : str;
}
usage:
用法:
console.log(nullToStr(null);
function nullToStr(str) {
return !str || 0 === str.length ? '' : str;
}
console.log(`The value which was null = ${nullToStr(null)}`);
console.log(`The value which was null = ${nullToStr(undefined)}`);
console.log(`The value which was null = ${nullToStr('')}`);
console.log(`The value which was null = ${nullToStr('asdasd')}`);
I think it will help and is much easier to use. Obviously, it is based on the other answers i found in this thread.
我认为它会有所帮助并且更容易使用。显然,它基于我在此线程中找到的其他答案。