比较数组时遇到麻烦

Trouble at comparing arrays

本文关键字:麻烦 遇到 数组 比较      更新时间:2023-09-26

我在控制器中有"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);
    }

但是有些函数如何不返回真或假,如何使其工作?

请救救我,因为我在 Angular 或直接从 PHP 的 Javascript Env 中重新开始。

您可以使用

Object.keys().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)

因为示例中的目标是对象而不是数组因此无法调用 indexOf 函数。

所以你很可能会得到:

未捕获的类型错误:target.indexOf 不是函数

要解决这个问题,你必须传递一个数组作为目标,而不是传递一个对象。