我正在使用Vue.JS和Laravel 5.2进行项目。
这是一个训练词汇的程序。所以我的Vue-Data-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
},
...
]
现在我有一个函数,该函数占用数组的长度,生成一个随机数,并从上面的数组中返回一个随机数:
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]
}
}
}
通常没有问题。但有时会出现错误消息:
Uncaught TypeError: Cannot read property 'process' of undefined
控制台说,该错误发生在我的getRandomWord()的if条件中if(this.words[i].process == 5)
。
知道为什么吗?进程的值始终为1、2、3、4或5。
到目前为止,谢谢!
Javascript数组的第一个索引为0,因此数组的最后一个索引为array.length - 1
。您用于生成索引的代码:
Math.floor((Math.random() * this.words.length) + 1);
有时会生成-的索引,该索引length
不存在。删除+1
,您应该会很好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句