Reputation: 15
I created an object movies and method as follows;
var movies = [
{
aa : "value01"
bb : 6.5
},
{
aa : "value02"
bb : 6
},
{
aa : "value02"
bb : 7.5
},
percentage:function(movieRating, scale){
return (movieRating/scale) * 100;
}
]
Accessing the object and method i tried to use the following approach;
theRating = (movies.percentage(movies[0].bb,10));
But running the script gives me a;
Uncaught SyntaxError: Unexpected token :
Actual code is in https://pastebin.com/9tvrSVJ1
The work around I did is found in https://pastebin.com/LkCwzWXn
Can someone point to me where the first version of the code is wrong.
Thanks in advance.
Upvotes: 0
Views: 35
Reputation: 370
Alternatively, if you (like me) don't like my previous answer and don't want to call the function inside the array, you could define it outside of the array just like you would any other function:
var movies = [
{
aa : "value01",
bb : 6.5
},
{
aa : "value02",
bb : 6
},
{
aa : "value02",
bb : 7.5
}
];
function percentage (movieRating, scale) {
return (movieRating / scale) * 100;
};
Then you could get your theRating
variable working by calling it like so:
theRating = (percentage(movies[0].bb, 10));
Upvotes: 0
Reputation: 73
try this: var movies = [ { aa : "value01", bb : 6.5 }, { aa : "value02", bb : 6 }, { aa : "value02", bb : 7.5 }, { percentage:function(movieRating, scale){ return (movieRating/scale) * 100; } }
]
and call the rating as theRating = movies[3].percentage(movies[0].bb, 10)
Upvotes: 0
Reputation: 370
The reason it isn't working is because you are trying to add a member to your array as if it was an object property. If you need to add a function to an array, you could do it like this:
(also, just to note, the error you are receiving is because the properties in your movies objects are not separated by commas.)
var movies = [
{
aa : "value01",
bb : 6.5
},
{
aa : "value02",
bb : 6
},
{
aa : "value02",
bb : 7.5
},
function (movieRating, scale){
return (movieRating / scale) * 100;
}
]
The function could then be called like so:
movies[3](1, 10);
I'm not sure of your implementation, but keeping the function in the array seems a bit strange if it's index is subject to change.
Upvotes: 2