开发者

Returning an array with decimal values in a javascript function

开发者 https://www.devze.com 2023-04-06 10:06 出处:网络
im having trouble returning an array that contains decimal values to a variable: function foo() { var coords = new Array(39.3,18.2);

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 erro开发者_开发百科r: Uncaught TypeError: Cannot read property '0' of undefined


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

精彩评论

暂无评论...
验证码 换一张
取 消