最近,我一直在学习 JavaScript。我遇到了一些 JavaScript 错误,上面写着“ _ _ is undefined”——这到底是什么意思,为什么会出现这种情况?我正在或多或少地寻找关于为什么会发生此错误以及可以采取哪些措施来解决它,或者为什么它通常首先会发生的解释。
例如:这里有两个函数(验证和 onSearch)--- 当我尝试运行“onSearch”时,我在控制台中得到 Ran SEARCH... 跟踪,但是它消失了。此外,当我通过 JSHero(尝试调试)运行它时,它告诉我“onSearch”是未定义的,我很好奇为什么。
我有一些使用 ActionScript 开发的经验,但我对 JavaScript 完全陌生。我非常感谢您对这实际上意味着什么的意见和解释。谢谢。
function validate(query){
console.log("Ran VALIDATE...");
// Trim whitespace from start and end of search query
while(query.charAt(0) === " "){
query = query.substring(1, query.length);
};
while(query.charAt(query.length-1) === ""){
query = query.substring(0, query.length-1);
};
console.log("Query length:",query.length);
console.log("Beginning conditional...");
// Check search length, must have 3 characters
if(query.length < 3){
console.log("Display alert...");
alert("Your search query is too small, try again.");
// (DO NOT FIX THE LINE DIRECTLY BELOW)
searchInput.focus();
}else{
console.log("Searching query...");
onSearch(query);
};
};
// Finds search matches
function onSearch(query){
//var search = function(query){
console.log("Ran SEARCH...");
// split the user's search query string into an array
var queryArray = query.join(" ");
// array to store matched results from database.js
var results = [];
// loop through each index of db array
for(var i=0, j=db.length; i<j; i++){
// each db[i] is a single video item, each title ends with a pipe "|"
// save a lowercase variable of the video title
var dbTitleEnd = db[i].indexOf('|');
var dbitem = db[i].tolowercase().substring(0, dbTitleEnd);
// loop through the user's search query words
// save a lowercase variable of the search keyword
for(var ii=0, jj=queryArray.length; ii<jj; ii++){
var qitem = queryArray[ii].tolowercase();
// is the keyword anywhere in the video title?
// If a match is found, push full db[i] into results array
var compare = dbitem.indexOf(qitem);
console.log("Compare:",compare);
if(compare != -1){
results.push(db[i]);
};
};
};
console.log("Hello");
results.sort();
// Check that matches were found, and run output functions
if(results.length === 0){
noMatch();
}else{
showMatches(results);
};
};
EDIT** "db" 在外部文件中定义。它只是一个 URL 的数组。它仍然说它也没有定义,这就是我要问的。
你如何定义 1) 一个变量 2) 一个函数