[英]Trouble at comparing arrays
我在控制器中有一個“ shared.checkedFacility”范圍數組,內容如下:
[14, 49, 93, 122, 44, 40, 88, 83, 65, 9, 38, 28, 8, 53, 125, 155]
而且我正在前端動態生成二維數組,例如,從' shared.facilities [$ parent。$ index] '的單個三維數組讀取為
{"0":56,"1":13,"2":49,"3":3,"4":11,"5":7,"6":19,"7":4,"8":9,"9":131,"10":21}
現在我正在ng-show參數中比較這兩個數組
containsAny(shared.checkedFacility,shared.facilities[$index])
函數定義如
function containsAny(source, target) {
console.log("contains called");
var result = source.filter(function(item) {
return target.indexOf(item) > -1
});
return (result.length > 0);
}
但是,該函數如何不返回true或false,如何使其起作用?
請救救我,因為我是從Angular或Javascript Env直接從PHP來的。
您可以使用Object.keys()
shared.facilities[$parent.$index]
.map()
從shared.facilities[$parent.$index]
創建一個數組
// `shared.checkedFacility` var checkedFacility = [14 , 49 , 93 , 122 , 44 , 40 , 88 , 83 , 65 , 9 , 38 , 28 , 8 , 53 , 125 , 155 ]; // shared.facilities[$parent.$index] var facilities = { "0": 56, "1": 13, "2": 49, "3": 3, "4": 11, "5": 7, "6": 19, "7": 4, "8": 9, "9": 131, "10": 21 }; // create an array having values contained in `facilities` var arr = Object.keys(facilities).map(function(prop, index) { return facilities[prop] }); console.log(arr) function containsAny(source, target) { console.log("contains called"); var result = source.filter(function(item) { return target.indexOf(item) > -1 }); return (result.length > 0); } // pass `arr` as second parameter to `containsAny` var res = containsAny(checkedFacility, arr); console.log(res)
您的函數失敗:
target.indexOf(item)
因為示例中的目標是Object而不是Array ,所以不能調用indexOf函數。
因此,您很可能會得到:
未捕獲的TypeError:target.indexOf不是函數
為了解決這個問題,您必須將Array作為目標而不是傳遞Object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.