简体   繁体   English

Javascript:如何连接将未定义或空值视为空的 2 个值

[英]Javascript: How to concatenate 2 values treating undefined or null values as empty

This is what I want:这就是我要的:

var str = data + unit; // data:"2", unit: "rem", I want str: "223"
var str = data + unit; // data:"2", unit: null, I want  str: "2"
var str = data + unit; // data:"2", unit: undefined, I want  str: "2"
var str = data + unit; // data:undefined, unit: "rem", I want str: "rem"

Input and output values are given in the comments against each line.输入和输出值在每行的注释中给出。 Normal concatenation appends "undefined" as a literal string.普通连接将“未定义”作为文字字符串附加。 I want undefined and null values to be treated as empty string我希望将未定义和空值视为空字符串

You can use the nullish coalescing operator to convert null or undefined to an empty string.您可以使用 nullish 合并运算符将 null 或 undefined 转换为空字符串。

var str = (data ?? "") + (unit ?? "");

For better browser support, you may want to use the logical or operator instead.为了获得更好的浏览器支持,您可能希望改用逻辑或运算符。

var str = (data || "") + (unit || "");

you can use a function你可以使用一个函数

const checkValue = value => value ? value :  '';
console.log(checkValue(null) + checkValue(null)) // ''

You can check the unit before concatenation.您可以在串联之前检查单位。 If its value is either undefined or null set it to empty, or whatever you want.如果它的值是 undefined 或 null 将它设置为空,或者任何你想要的。 Then you can concatenate.然后就可以串联了。

function concatenate(data, unit) {
    if(unit == undefined || unit == null) {
        unit = "";
    }
    return data + " " + unit;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM