0

I'm trying to push "lene"(its just a test sample) into the variable "q". For some reason this is what my browser mentions:

Javascript highscore.html:24 Uncaught TypeError: undefined is not a function
Javascript highscore.html:145 Uncaught TypeError: Cannot read property 'length' of undefined

The second error, on line 145 is a because of the first error. I have marked line 24 in the comments here:

var q = [{
    TernRank: 2,
    TernVan: '03/12/2014',
    TernTot: '01/01/2015',
    TernDagen: 1
}, {
    TernRank: 3,
    TernVan: '08/01/2014',
    TernTot: '01/01/2015',
    TernDagen: 1
}, {
    TernRank: 1,
    TernVan: '03/12/2014',
    TernTot: '01/01/2015',
    TernDagen: 1
}, {
    TernRank: 4,
    TernVan: '03/12/2014',
    TernTot: '01/01/2015',
    TernDagen: 1
}];




DAY = 1000 * 60 * 60 * 24

for (i = 0; i < 4; i++) {
    d1i = new Date(q[i].TernVan)
    d2i = new Date(q[i].TernTot)

    days_passedi = Math.round((d2i.getTime() - d1i.getTime()) / DAY)
    q[i].splice(3, 0, "Lene"); //This is line 24
};

The line 24 does works if I remove the "[i]". Does anyone know why it's causing the error or/and how to fix it?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Rick Standaert
  • 98
  • 2
  • 14
  • 4
    q[i] isn't an array. What are you trying to do ? – Denys Séguret Jan 05 '15 at 08:58
  • You do declare `i`, `DAY`, `d1i`, `d2i`, `days_passed1`, and such somewhere, right? Because if not, your code is falling prey to [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html). – T.J. Crowder Jan 05 '15 at 09:07

1 Answers1

0

q is an array, and q[i] is an object.

Only arrays have the method .splice by default: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

If you wish to add 'Lene' to the q array, the easiest way would be:

q.push('Lene');

Alternatively if you really want to make the splice work, you may want to do this:

q.splice(i, 0, 'Lene');

Which will add the element 'Lene' at index i in the q array. Or you may want to do something like this:

q.splice(q.length + 1, 0, 'Lene');

Which is basically the same as q.push

Rajit
  • 808
  • 5
  • 9