Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can pass an extra parameter via the function used by the Array.forEach method?

I've an Array :

var allchildsAr = new Array();

and i'm filling it with an object having a parent property(an object) and a chlds property which is an Array.

Here is the code to fill the array :

Ti.API.info("*****allchildsAr["+level+"] is null and "+elmn+" children will be added to it ");
allchildsAr[level] = new Array({parent:elmn,chlds:elmn.getChildren()}); 

and here is how i tried to display the array after the add :

  Ti.API.info("*****allchildsAr["+level+"] after add");
allchildsAr[level].forEach(logArrayJsonElements);

the logArrayJsonElements method is the following :

function logArrayElements(elemnt, indx, array) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.id);
}

function logArrayJsonElements(elemnt, indx, array) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.parent.id);
    elemnt.chlds.forEach(logArrayElements);
}

this works fine but what i want is to pass the parent element through logArrayElements so i can display it as a parent of the array's displayed element (and later to do another stuff with it..)

function logArrayElements(elemnt, indx, array, parent) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.id+" child of :"+parent);
}

and now i'm confused because when the logArrayElements is called inside the forEach it doesn't take arguments and they are passed implicitly and if i add the parent as i did it be taken for another parameter(normally the element parameter) and anyway i'm not passing any of them so how i will get the parent inside the function and make the foreach pass it like other parameters ?

like image 902
Bardelman Avatar asked Feb 15 '23 05:02

Bardelman


2 Answers

You can do this by modifying your forEach line to:

function logArrayJsonElements(elemnt, indx, array) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.parent.id);
    elemnt.chlds.forEach(function (element, index, arr) {
        logArrayElements(element, index, arr, elemnt.parent.id);
    });
}
like image 88
tewathia Avatar answered Feb 17 '23 03:02

tewathia


Well, if element already has a parent property on it, then why not just use element.parent in logArrayElements?

Assuming that the elements are not of the same data structure, then bind also partially applies, so you could do this:

function logArrayElements(parent, element, index, array) {
    console.log("Element at [%s] : %s child of %s", index, element.id, parent);
}

function logArrayJsonElements(element, index, array) {
    element.chlds.forEach(logArrayElements.bind(null, element.parent));
}
like image 36
Sean Vieira Avatar answered Feb 17 '23 01:02

Sean Vieira