nuis
nuis

Reputation: 95

(javascript) Calling a method on an object inside an array

I am not sure i named the title properly. Let me explain my little problem.

My code snipppet is pretty short:

var myArray= new Array([new Date()],[123],[abc]);
var time = myArray[0].getTime()

I want the time saved in the object inside the array to be written to the "time" variable. I just thought this would work but i get an error.

Uncaught TypeError: myArray[0].getTime is not a function

Apparently i am doing it wrong, but i have no idea what is the problem and how to do it right.

Upvotes: 4

Views: 743

Answers (3)

Luan Nico
Luan Nico

Reputation: 5917

The code you used creates an array with arrays inside:

var myArray= new Array([new Date()],[123],[abc]); // [[new Date()],[123],[abc]]

So you would have to call

myArray[0][0].getTime()

You probably wanted to do

var myArray = new Array(new Date(),123,abc); // [new Date(),123,abc]

Or simply

var myArray = [new Date(),123,abc];

As a tip, when you get these errors, try console.loging the variables. You would see the date you expected was actually an array with a single position, and would easily found out the error :)

Upvotes: 1

Slava N.
Slava N.

Reputation: 596

You define array of arrays [[], [], []], so to get date element you should do this:

var myArray= new Array([new Date()],[123],['abc']);
var time = myArray[0][0].getTime();

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

Its inside of another array:

var time = myArray[0][0].getTime();
//                   ^^^

Working example:

var myArray = new Array([new Date()], [123], ['abc']),
    time = myArray[0][0].getTime();

alert(time);

Upvotes: 3

Related Questions