如何在一个数组由非定义对象组成的角度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
条件。
答
使用Array.every ...
var allAreUndefined = joinedArray.every(function(value) {
return value === undefined;
});
要检查数组定义你需要的typeof使用,如答案建议this question。
答
使用字符串数组,正则表达式替换和空字符串比较。例如:
/* 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
*/
参考
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every – Bergi
[检查数组是否为空或存在]的可能重复(http://stackoverflow.com/ question/11743392/check-if-array-is-empty-or-exists) –