im having trouble returning an array that contains decimal values to a variable:
function foo() {
var coords = new Array(39.3,18.2);
console.log(coords[1]); //successfully logs 18.2
return coords;
}
but then...
var result = foo();
alert(result[0]);
that last one throws this error: Uncaught TypeError: Cannot read property '0' of undefined
im having trouble returning an array that contains decimal values to a variable:
function foo() {
var coords = new Array(39.3,18.2);
console.log(coords[1]); //successfully logs 18.2
return coords;
}
but then...
var result = foo();
alert(result[0]);
that last one throws this error: Uncaught TypeError: Cannot read property '0' of undefined
Share Improve this question edited Sep 20, 2011 at 18:42 Andres SK asked Sep 20, 2011 at 18:19 Andres SKAndres SK 11k27 gold badges96 silver badges158 bronze badges 2-
1
Shouldn't that be
alert(result[0])
? Everything else looks fine - I'd say the problem is somewhere else in your code. – Matthew Commented Sep 20, 2011 at 18:24 - That's not the issue. Ill correct the question. – Andres SK Commented Sep 20, 2011 at 18:44
3 Answers
Reset to default 4You need to put parentheses around the argument to the alert function.
alert(result[0]);
As other people mentioned, alert is a function and needs parenthesis
alert(result[0])
That said, there are some extra points to note:
1) Use array literal syntax instead of new Array
var coords = [1.23, 3.45];
Its faster and new Array has some edge cases.
2) Most browsers have developer tools (usually reacheable by F12). This allows you to use the much more convenient console.log instead of alert.
The problem is the missing parentheses around the alert statment
try
alert (result[0]);