简体   繁体   English

比较数组时遇到问题

[英]Trouble at comparing arrays

I have 'shared.checkedFacility' scope array in controller which read something like: 我在控制器中有一个“ shared.checkedFacility”范围数组,内容如下:

[14, 49, 93, 122, 44, 40, 88, 83, 65, 9, 38, 28, 8, 53, 125, 155]

and i am dynamically generating two dimensional array in front end where, for example, single dimentional array from ' shared.facilities[$parent.$index] ' read like 而且我正在前端动态生成二维数组,例如,从' 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}

Now i am comparing this two array in ng-show argument like 现在我正在ng-show参数中比较这两个数组

containsAny(shared.checkedFacility,shared.facilities[$index])

Where as function defination is like 函数定义如

function containsAny(source, target) {
        console.log("contains called");
        var result = source.filter(function(item) {
            return target.indexOf(item) > -1
        });
        return (result.length > 0);
    }

But some how this function is not returning true or false, how to make it work? 但是,该函数如何不返回true或false,如何使其起作用?

Please rescue me since i am afresh here in Angular or in Javascript Env straight from PHP. 请救救我,因为我是从Angular或Javascript Env直接从PHP来的。

You can use Object.keys() , .map() to create an array from shared.facilities[$parent.$index] 您可以使用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) 

Your function is failing on: 您的函数失败:

target.indexOf(item)

because target in your example is an Object and not an Array , so you can't call indexOf function. 因为示例中的目标Object而不是Array ,所以不能调用indexOf函数。

So you are most likely getting: 因此,您很可能会得到:

Uncaught TypeError: target.indexOf is not a function 未捕获的TypeError:target.indexOf不是函数

To solve that, you have to pass an Array as target instead of passing an Object. 为了解决这个问题,您必须将Array作为目标而不是传递Object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM