最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Returning an array with decimal values in a javascript function - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

You 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]);
发布评论

评论列表(0)

  1. 暂无评论