0

I have this code that fetches data and puts it into an array:

    this.$httpGetTest(this.test.testId)
        .success(function (data: ITestQuestion[]) {
            self.test.qs = data; 
        });

It works and populates the array starting with self.test.qs[0].

However many times my code references this array (which contains a list of questions 1...x)

I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:

self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.

Ideally I would like to do this by putting something after the self.test.qs = and before data.

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • Splice the null value into the array before you assign it to `self.test.qs`. Take a look at http://stackoverflow.com/questions/586182/insert-item-into-array-at-a-specific-index – hotforfeature Oct 08 '14 at 16:47

4 Answers4

1

You need to use Splice(), It works like:

The splice() method changes the content of an array, adding new elements while removing old elements.

so try:

self.test.qs.splice(0, 0, null);

Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.

Here is demo:

var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";

alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
1

Push values at start of array via unshift

self.test.qs.unshift(null); 
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
0

You can start off with an array with a null value in it, then concat the questions array to it.

var arr = [null];
arr = arr.concat(data);
Lucas Penney
  • 2,624
  • 4
  • 27
  • 36
0

You could do something like:

x = [null].concat([1, 2, 3]);

Though there isn't anything wrong with doing something like:

x[index-1]

I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.

Jack Culhane
  • 763
  • 7
  • 11