0

I am working on a project with Vue.JS and Laravel 5.2.

It is a program to train vocabulary. So there is an array in my Vue-Data-Object, containing wordpairs. Each wordpair is stored as an object:

"words": [
    {
      "lang1": "Haus",
      "lang2": "house",
      "lang1_hint": "",
      "lang2_hint": "",
      "image_url": "",
      "tries": 0,
      "fails": 0,
      "process": 1
    },
    {
      "lang1": "Feuer",
      "lang2": "fire",
      "lang1_hint": "",
      "lang2_hint": "",
      "image_url": "",
      "tries": 0,
      "fails": 0,
      "process": 5
    },
    ...
]

Now i have a function, which takes the length of the array, generates a random number and returns a random number out of the array above:

getRandomWord: function(){
    var i = Math.floor((Math.random() * this.words.length) + 1);
    if(this.words[i].process == 5){
        return this.getRandomWord();
    } else {
        return {
            index: i,
            content: this.words[i]
        }
    }
}

Mostly there is no problem. But sometimes, there occurs an error saying:

Uncaught TypeError: Cannot read property 'process' of undefined

The console says, that the error occurs in the if-condition of my getRandomWord() if(this.words[i].process == 5).

Any idea why? The value of process is always 1, 2, 3, 4 or 5.

Thanks so far!

3 Answers 3

1

The first index of a Javascript array is 0, so the last index of your array is array.length - 1. Your code for generating the index:

  Math.floor((Math.random() * this.words.length) + 1);

will sometimes generate an index of length - which does not exist. Remove the +1 and you should be good.

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

1 Comment

Oh man... thanks! I know that an array begins at 0 but this was not the direction I was looking for a solutions.
1

Im pretty sure that you have problem in here

  var i = Math.floor((Math.random() * this.words.length) + 1);

Remove +1 and you should be good to go.Remember arrays starts with index 0

Comments

1

The error means that this.words[i] is undefined for some i.

You should write

var i = Math.floor((Math.random() * this.words.length));

Comments

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.