4

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.

1
  • the matter is you're defining an imbricated arrays (arrays inside array) Commented Mar 13, 2016 at 16:18

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, i was a fool on creating an array in array. Was not intended, and i did not realize.
1

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();

1 Comment

Thank you, i will be more alert on handling arrays in the future.
1

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 :)

1 Comment

"You probably wanted to do" -- haha, yes, what a shame, but you are right. Thank you for explaining.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.