Returning Arrays and ChildNodes

2019-08-31 14:06发布

问题:

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();