字符串中的 JavaScript 空值
javascript null value in string
在javascript中,我有以下内容:
var inf = id + '|' + city ;
如果 id 或 city 为空,则 inf 将为空。
如果 id 或城市为空,是否有任何巧妙的说法,然后为空。
我知道在 c# 中你可以执行以下操作:
var inf = (id ?? "") + (city ?? "");
javascript中有什么类似的方法吗?
怎么样:
var inf = [id, city].join('|');
编辑:您可以在连接之前删除"空白"部分,这样如果 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
总长镜头,但试试这个:
var inf = (id || "") + "|" + (city || "");
var inf = (id == null ? '' : id) + '|' + (city == null ? '' : city)
function nullToStr(str) {
return !str || 0 === str.length ? '' : str;
}
用法:
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')}`);
我认为它会有所帮助,并且更容易使用。显然,它基于我在此线程中找到的其他答案。
var inf = (id && city) ? (id+"|"+city) : "";
等效于 c# var inf = (id ?? "") + (city ?? "");
(如果 id
和 city
可为空)为
var inf = (id || '') + (city || '');
这称为"短路评估"。可空性在javascript中不是问题(在js中所有变量都是可为空的),但是必须分配id
和city
(但不需要值,如var id, city
)。
if (id != ""){
inf = id;
if (city != ""){ inf += " | " + city ;}
}
else
inf= city;
相关文章:
- JavaScript-HTML表单到JSON(空值)和格式
- 从数组空值到浏览器刷新的 Javascript 变量
- 如何在 JavaScript 中找出对象中的空值
- 使用 json_encode 将数组从 PHP 传递到 JavaScript 会显示空值
- 用于删除空值的 JavaScript 函数
- 删除添加空值的 Javascript 对象项
- 检查 javascript 数组是否不仅包含空值
- 用于处理空值的 JavaScript 说明
- Javascript下拉列表工作,但显示空值
- 如何在 JavaScript 中管理 PHP 代码中的空值
- Javascript 在 Internet Explorer 中破坏属性的空值 - 如何让 IE 忽略这一点
- 我应该使用 if-then-else 或 and or 运算符来检查 Javascript 中的空值吗?
- JavaScript 单击文本框中的函数空值
- 字符串中的 JavaScript 空值
- 将空值从PHP传递到Javascript函数
- 如何使用javascript验证空值
- 空值的JavaScript行为是什么
- JavaScript 的类型函数是否检查空值
- javascript空值-它是一个对象吗
- JavaScript空值错误