Javascript 如何用空字符串替换 undefined
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25876247/
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
how to replace undefined with a empty string
提问by texas697
I am using jsPdf. When a field has been left blank "undefined" is printed on the pdf. I would like to replace that with a empty string. I am trying to use a if statement but I am not getting it.
我正在使用jsPdf。当一个字段留空时,“未定义”会打印在 pdf 上。我想用空字符串替换它。我正在尝试使用 if 语句,但我没有得到它。
doc.text(30, 190, "Budget : $");
if ($scope.currentItem.JobOriginalBudget == "undefined") {
doc.text(50, 190, " ");
}
else {
var y = '' + $scope.currentItem.JobOriginalBudget;
doc.text(50, 190, y);
};
采纳答案by apsillers
undefinedis a primitive value. Instead of comparing against the identifier undefined, you're comparing against the 9-character string"undefined".
undefined是一个原始值。您不是与 identifier 进行比较,而是undefined与 9 个字符的字符串" undefined"进行比较。
Simply remove the quotes:
只需删除引号:
if ($scope.currentItem.JobOriginalBudget == undefined)
Or compare against the typeofresult, which isa string:
或者与typeof结果进行比较,这是一个字符串:
if (typeof $scope.currentItem.JobOriginalBudget == "undefined")
回答by Nuno Costa
As per this answerI believe what you want is
根据这个答案,我相信你想要的是
doc.text(50, 190, $scope.currentItem.JobOriginalBudget || " ")
回答by theDarse
simply remove the "== 'undefined'"
只需删除“=='未定义'”
if (!$scope.currentItem.JobOriginalBudget) {
doc.text(50, 190, " ");
}
回答by Abdullah Pariyani
var ab = {
firstName : undefined,
lastName : undefined
}
let newJSON = JSON.stringify(ab, function (key, value) {return (value === undefined) ? "" : value});
console.log(JSON.parse(newJSON))
<p>
<b>Before:</b>
let ab = {
firstName : undefined,
lastName : "undefined"
}
<br/><br/>
<b>After:</b>
View Console
</p>
回答by Maxime
If item is an Object use, this function :
如果 item 是 Object 使用,则此函数:
replaceUndefinied(item) {
var str = JSON.stringify(item, function (key, value) {return (value === undefined) ? "" : value});
return JSON.parse(str);
}

