0

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.

3 Answers 3

1

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.

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

Comments

0

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)

Comments

0

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

1 Comment

Thank you very much for the reply. Will be trying out the code suggestion that you mentioned and will update this post once I am done.

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.