Returning Arrays and ChildNodes

偶尔善良 提交于 2019-12-11 21:42:56

问题


I have the following code:

var actionsAllowed = $(packet).find('actionsAllowed').get();

var actionArray = $(actionsAllowed).each(function () {
    var actionNodes = this.childNodes;
    var actionNumber = actionNodes.length;
    var array = new Array(actionNumber)

    for (var i = 0; i < actionNodes.length; i++) {
        var action = actionNodes[i].nodeName
        array[i] = action
        console.log(action);
    }
    return array;
});

This searches the packet (XML) for "actionsAllowed" and returns it as "[actionsAllowed]".

I am then trying to create an array with each of the actions listed in the array.

The "this" becomes "actionsAllowed" without the "[ ]" and that allows it to return the child nodes in the form "NodeList[ActionOne, ActionTwo, ActionThree]". I then get the length of the NodeList and create an array of that length.

I then iterate over the NodeList and add each to the array.

By the end, it returns the array as "[ActionOne, ActionTwo, ActionThree]", which is great!

BUT - this is the problem:

The variable "actionArray" becomes "Object[actionsAllowed]", instead of the array.

Any idea why this is please? I have a theory but I'm unable to fix it =(

Thank you!


回答1:


$(actionsAllowed).each returns the first element of the iteration. You seem to want this :

var actionArray = [];
$(actionsAllowed).each(function () {
    var actionNodes = this.childNodes;
    var actionNumber = actionNodes.length;
    var array = new Array(actionNumber)

    for (var i = 0; i < actionNodes.length; i++) {
        var action = actionNodes[i].nodeName
        array[i] = action
        console.log(action);
    }
    actionArray.push(array);
});    

EDIT : If what you want is a big array instead of an array of arrays, change it to

var actionArray = [];
$(actionsAllowed).each(function () {
    var actionNodes = this.childNodes;
    for (var i = 0; i < actionNodes.length; i++) {
        var action = actionNodes[i].nodeName
        actionArray.push(action);
        console.log(action);
    }
});    



回答2:


Here's another alternative:

var actionArray = $('actionsAllowed > *').map(function (el) { 
    return el.nodeName; 
}).get();


来源:https://stackoverflow.com/questions/19933748/returning-arrays-and-childnodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!