Thursday, 15 January 2015

arrays - Javascript removing elements in forEach -



arrays - Javascript removing elements in forEach -

this question has reply here:

looping through array , removing items, without breaking loop 7 answers

i'm trying create function can remove element within foreach loop.

the function:

loopandedit = function(array,callback) { var helper = { data:{}, get:function() { homecoming helper.data; }, remove:function() { index = array.indexof(helper.data); array.splice(index,1); homecoming true; } }; temparray = array; temparray.foreach(function(row) { helper.data = row; callback(helper) }); }

to test loop through array , seek remove elements:

names = ['abe','bob','chris']; loopandedit(names,function(helper){ console.log('working on ' + helper.data); helper.remove(); }); console.log(names);

the output is:

working on abe working on chris [ 'bob' ]

i expect output like:

working on abe working on bob working on chris []

i have feeling may helper.remove() causing problem i'm unsure @ point.

thanks help!

that because foreach loop not able loop through 3 elements removing 1 item within foreach loop.

so, foreach loop went through index 0 , 1 removed index 1. @ point length of array changed n-1 index within loop still same.

in order create re-create of array doesn't create changes in original array.

do -

var temparray = names.slice(0);

instead of -

var temparray = names;

javascript arrays node.js foreach

No comments:

Post a Comment