如何在一个数组由非定义对象组成的角度js中声明`if`条件

如何在一个数组由非定义对象组成的角度js中声明`if`条件

问题描述:

我有一个名为joinedArray的数组。在一种情况下,它的值为[undefined, undefined]如何在一个数组由非定义对象组成的角度js中声明`if`条件

我写了一个if condition像:

if(joinArray === undefined){ 
    vm.selectedFriends = []; 
    angular.forEach($scope.contacts, function(contact){ 
     if (contact.selected) 
     vm.selectedFriends.push(contact.email); 
    }); 

    $http({ 
     url: 'http://192.168.2.8:7200/api/creatList', 
     method: 'POST', 
     data: {wData:userData, uId:vm.uid, userName:vm.uName, email:vm.selectedFriends} 
    }).success(function(res) { 
     console.log("success"); 
    }, function(error) { 
     console.log(error); 
     alert('here'); 
    }); 
    $mdDialog.hide(userData); 
} else { 
    $http({ 
     url: 'http://192.168.2.8:7200/api/sendMail', 
     method: 'POST', 
     data: {wData:userData, email:joinArray, uId:vm.uid, userName:vm.uName} 
    }).success(function(res) { 
     console.log("success"); 
    }, function(error) { 
     console.log(error); 
     alert('here'); 
    }); 
    $mdDialog.hide(userData); 
} 

有时joinedArray回报像[value, undefined][undefined, value]。但是,只有当两个值都未定义时,才会传递给if条件,否则应该转到else条件。

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every – Bergi

+0

[检查数组是否为空或存在]的可能重复(http://stackoverflow.com/ question/11743392/check-if-array-is-empty-or-exists) –

使用Array.every ...

var allAreUndefined = joinedArray.every(function(value) { 
    return value === undefined; 
}); 

要检查数组定义你需要的typeof使用,如答案建议this question

+0

我编辑了我的问题,如果条件如何使用。 – Kevin

+0

我之前使用过这个,如果条件和我做了如果条件像if(joinArray === allAreUndefined)但它不工作它会去其他条件。 – Kevin

使用字符串数组,正则表达式替换和空字符串比较。例如:

/* If a stringified array consists of null values, convert it to an empty string, and return null 
 
    */ 
 
    if (JSON.stringify(Array(10)).replace(/^\[(null[,\]])+/,"") === "") 
 
     { 
 
     console.log(null); 
 
     } 
 
    else 
 
     { 
 
     console.log(NaN); 
 
     }

或者更具体地说:

"use strict"; 
 

 
/* evaluate a stringified array to get the evaled values */ 
 
var foo = Function("return eval(JSON.stringify(Array(10)).replace(/null/g, undefined))")(); 
 

 

 
if (JSON.stringify(foo).replace(/^\[(null[,\]])+/,"") === "") 
 
    { 
 
    console.log("null"); 
 
    } 
 
else 
 
    { 
 
    console.log("not null"); 
 
    } 
 

 

 
/* 
 
Use foo.indexOf(null) before all this to avoid false positives 
 
*/

参考