我有一个由输入<form>
var chatArr = [];
function input() {
var chat = document.getElementById("yousay").value;
chatArr.push(chat);
var words = chatArr.join(' ').match(/\S+/g);
if(chat.length == 0){
console.log("Mithras hears you")
}
else if(words.length > 1){
return words;
}
else{
console.log(chat)
};
}
然后:
function setIntersection(a, b) {
var result = [];
for (var i = 0; i < a.length; i++) {
if (b.indexOf(a[i]) !== -1 && result.indexOf(a[i]) === -1) {
result.push(a[i]);
}
}
return result;
}
,反过来,进入这个功能:
Song.prototype.lyricsIntersect = function(input) {
var bestSong = null;
var bestCount = -Infinity;
for (var i in songs) {
var currentCount = setIntersection(songs[i].lyrics, input()).length;
(...)
然而,当页面加载时,表单显然是空的,所以我得到:
Uncaught TypeError: Cannot read property 'indexOf' of undefined
如何在加载页面时阻止此错误?
答案 0 :(得分:0)
在获取Array索引之前检查数组长度,
if(result.length > 0)
{
if (b.indexOf(a[i]) !== -1 && result.indexOf(a[i]) === -1) {
result.push(a[i]);
}
}
答案 1 :(得分:0)
尝试像这样声明你的数组:
var result = new Array(a.length);
答案 2 :(得分:0)
尝试为if语句添加一些保护,如下所示:
function setIntersection(a, b) {
var result = [];
for (var i = 0; i < a.length; i++) {
if (
typeof b != "undefined" && /* added protection */
b.indexOf(a[i]) !== -1 && result.indexOf(a[i]) === -1) {
result.push(a[i]);
}
}
return result;
}
现在,由于此代码位于循环内,因此,如果b未定义,则可以避免任何迭代,因此:
function setIntersection(a, b) {
var result = [];
/* added protection */
if(typeof b != "undefined") return result;
for (var i = 0; i < a.length; i++) {
if (b.indexOf(a[i]) !== -1 && result.indexOf(a[i]) === -1) {
result.push(a[i]);
}
}
return result;
}
基本上,应考虑功能参数的每个值,并在必要时添加保护