使javascript变量可以为空

时间:2018-06-08 07:25:59

标签: javascript

嗨我有以下功能可以从变量suggest中删除重复项,但有时我收到的JSON.parse变量数据为空,下面的代码因function suggestData(data){ var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work. suggest = JSON.parse(data); for (var i = suggest.length - 1; i >= 0; i--) { for (var j = 0; j < arrString.length; j++) { if (suggest[i] === arrString[j]) { suggest.splice(i, 1); } } } 而无效函数如何使它变量接受空数据,以便下面的代码仍然可以运行没有任何问题。任何帮助将不胜感激!

runef --model-location "model path" --scenario-tree-location "scenario data path" --solve --solver glpk

5 个答案:

答案 0 :(得分:1)

有条件地将length设为,

var length = suggest? suggest.length: 0;

&#13;
&#13;
function suggestData(data){

    var suggest = [];
    suggest = JSON.parse(data);
    var length = suggest? suggest.length: 0;
    for (var i = length - 1; i >= 0; i--) { 
        for (var j = 0; j < arrString.length; j++) {
            if (suggest[i] === arrString[j]) {
                suggest.splice(i, 1);
            }
        }
    }
}
suggestData(null);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

function suggestData(data){

var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.

如果(数据)     suggest = JSON.parse(data);

for (var i = suggest.length - 1; i >= 0; i--) { 
    for (var j = 0; j < arrString.length; j++) {
        if (suggest[i] === arrString[j]) {
            suggest.splice(i, 1);
        }
    }
}

只需在解析行上添加if条件即可 用上面的代码编写::

如果(数据)     suggest = JSON.parse(data);

答案 2 :(得分:1)

最简单的:

if(!data || !suggest)
    return;

答案 3 :(得分:1)

您可以在if条件中设置function suggestData(data){ var suggest = []; if(data){ suggest = JSON.parse(data); } for (var i = suggest.length - 1; i >= 0; i--) { for (var j = 0; j < arrString.length; j++) { if (suggest[i] === arrString[j]) { suggest.splice(i, 1); } } } 以检查数据是否存在

function suggestData(data) {
   if(!data){
      return false;
    }
  //other code here
  ...
}

如果你不想在数据为空时执行它,你也可以简单地结束这个功能:

{{1}}

答案 4 :(得分:0)

let array = [1,2,3,8,3,4,4,5]
const removeDuplicateItems = arr => [...new Set(arr)];

console.log(removeDuplicateItems(array))

如果您只想删除数组中的重复项,则可以尝试Set,这非常方便

即使array为空或为空,此方法removeDuplicateItems仍然有效