如何在复杂的javaScript数组对象中搜索

时间:2018-04-25 03:07:21

标签: javascript angularjs lodash

我有点困惑。我在指令中有以下代码:

NavTabsDirective.prototype.addPane = function (pane) {
        if (!_.isObject(pane) || "Pane" !== pane.constructor.name) {
            throw new TypeError("pane must be an instance of Pane");
        }

        if (_.isUndefined(this.FirstPane)) {
            this.FirstPane = pane;
        }
        
        this.Panes[pane.name] = pane;
    };

当我在this.Panes数组中查看调试器时,我看到类似的内容:

this.Panes[name1] = paneObject -- with properties
this.Panes[name2] = paneObject -- with its properties

我想了解如何搜索此数组。说,这是我的代码:

let invalid = (_.findIndex(this.Panes, { 'isValid': false })>=0);

我注释掉了,因为它无法找到isValid为false的窗格,尽管我可以在该数组中看到这样的窗格。

所以,我的困惑来自于Panes数组对象具有访问每个窗格对象的名称,因此我不知道如何正确搜索它。如何检查窗格中的无效?

3 个答案:

答案 0 :(得分:1)

除非pane.name是数字,否则this.panes中的窗格不是数组,它是一个对象,您可以使用它的键并将其缩小为一个值:

const result = Object.keys(this.Panes).reduce(
  (all,key)=>all && this.Panes[key].isValid,
  true
)

答案 1 :(得分:0)

在这里查看几个线程后找出解决方案:



for (let pane in this.Panes) {
                if (this.Panes[pane].isValid === false) {
                    invalid = true;
                    break;
                }
            }




效果很好。

答案 2 :(得分:0)



var Panes = ["Hello","World"];
var PanesLength = Panes.length;
for (var i = 0; i < PanesLength; i++) {
    if(Panes[i] == "Hello"){
      alert(Panes[i]);
    }
}
&#13;
&#13;
&#13;