Kim Gysen Kim Gysen - 2 years ago 175
Javascript Question

Get next array element

Say I want to replace an array of objects with an array of decorators:

var arr = [{id:1, text: "text1"}, {id:2, text: "text2"}, {id:3, text: "text3"}];

arr.forEach(function(el, idx){
var newEl = new NewEl(, el.text, arr[idx + 1], idx);
arr[idx] = newEl;
}, this);


function NewEl(id, text, nextEl, idx){ = id;
this.text = text; = nextEl;

will still refer to the old object, not the next item in the array (whatever that element).

How do I pass a reference to the next element (location) in the array to the constructor function?

Note: If possible, I'd prefer not to use a workaround by modifying the logic within the loop (workaround involving setting 'next' on the previous element on next iteration).

Is it possible?

Answer Source

You can't use a reference before that reference is created (i'm sure that's obvious). So it is difficult to solve without changing the loop to look at the previous. However, if you must solve it without looking at the previously created items, you could change your NewEl to receive both the full array and next index instead of an actual reference. Something like the following:

function NewEl(id, text, arr, nextIndex){ = id; 
    this.text = text; 
    this.arr = arr;
    this.nextIndex = nextIndex; 

NewEl.prototype.getNext = function(){
    return this.arr[this.nextIndex];

The idea being that the only way you can use a reference prior to creating it, is to actual not use it, but store a way of accessing it later. However this is a terrible way of doing this, as any change to the array will break the getNext() function.

tldr; You should really just change the loop to reference the previous item, from the next iteration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download