how do i write iteration inside jquery plugin with array.shift() and pass array to next loop unchanged?

StackOverflow https://stackoverflow.com/questions/23483154

Question

Im writing a jquery plugin which will iterate throw the passed array and recursively call simple function with passed array.shifted,

    function test (arr, el){
    console.log(el, arr);
    if ( arr.length > 0 ) {
        arr.shift();
        test(arr, el);
    }
}
$.fn.someFunc = function( config, cb ){
    return this.each(function(i, el){
        test(config, i);
    })  
};

and it works fine if i'm calling someFunc() on jquery with single element selector: $('#singleElement').someFunc(['one','two','tree']), but if i call it on jquery with multiple element selector like $('.class').someFunc(['one','two','tree']) (assuming that i have 2+ divs with class .class) arr object goes to second element already empty.

so does anyone have any idea how to make arr local for each loop and then shift it or better solution for this kind of a problem if i am getting the problem wrong. thnx

Was it helpful?

Solution

Instead of

if (arr.length > 0) {
   arr.shift();
   test(arr, el);
}

Write

if (arr.length > 0) {
   test(arr.slice(1), el);
}

arrays are passed as references, so when you shift element it's shifted from array reference (it's one object).

when calling array.slice it duplicates array sliced in chunks you want, so array is remaining unchanged.

or change

test(config, el);

to

test(config.slice(0), el);

in someFunc. test Fn will get duplicated array and will shift elements from one reference for each element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top