2016-09-23 6 views
-1

配列はjoinedArrayです。あるケースでは、値は[undefined, undefined]です。配列がAngular 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); 
} 

時には[value, undefined]または[undefined, value]ようjoinedArray戻ります。しかし、両方の値が定義されていない場合にのみ、ifの条件に渡されます。そうでない場合は、elseの条件になります。

+0

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

+0

[配列が空であるかどうかを確認する](http://stackoverflow.com/)が重複している可能性があります。質問/ 11743392 /配列が空であるかどうかチェックする) –

答えて

1

使用Array.every ...

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

配列は、あなたがthis questionへの答えで提案されているように、typeof演算を使用する必要が定義されているかどうかを確認するには。

+0

私はその条件のためにどのように使用するか質問を編集しました。 – Kevin

+0

if(joinArray === allAreUndefined)のような条件で条件と私が作ったが、それがうまく動作しない場合、これを前に使用しました。 – Kevin

0

文字列化された配列、正規表現の置き換え、および空の文字列の比較を使用します。例えば:

/* 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 
 
*/

参照

関連する問題