how to replace undefined with a empty string

▼魔方 西西 提交于 2019-12-06 18:13:54

问题


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.

 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);
    };

回答1:


undefined is a primitive value. Instead of comparing against the identifier undefined, you're comparing against the 9-character string "undefined".

Simply remove the quotes:

if ($scope.currentItem.JobOriginalBudget == undefined)

Or compare against the typeof result, which is a string:

if (typeof $scope.currentItem.JobOriginalBudget == "undefined")



回答2:


As per this answer I believe what you want is

doc.text(50, 190, $scope.currentItem.JobOriginalBudget || " ")



回答3:


simply remove the "== 'undefined'"

if (!$scope.currentItem.JobOriginalBudget) {
    doc.text(50, 190, " ");
}



回答4:


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>



回答5:


If item is an Object use, this function :

replaceUndefinied(item) {
   var str =  JSON.stringify(item, function (key, value) {return (value === undefined) ? "" : value});
   return JSON.parse(str);
}


来源:https://stackoverflow.com/questions/25876247/how-to-replace-undefined-with-a-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!