当使用JavaScript时“未定义”某些内容时,这意味着什么?

What does it mean when something is "not defined" when using JavaScript?

本文关键字:未定义 意味着 什么 JavaScript      更新时间:2023-09-26

最近,我一直在学习JavaScript。我遇到了一些JavaScript错误,说"__是未定义的" - 这到底是什么意思,为什么会出现这种情况?我或多或少地在寻找有关为什么会发生此错误以及可以采取哪些措施来修复它,或者为什么它通常首先发生的原因。

例如:这里有两个函数(验证和搜索) --- 当我尝试运行"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);
    };
};

编辑**"db"在外部文件中定义。它只是一个 URL 数组。它仍然说它没有定义,这就是我要问的。

你如何定义1) 一个变量2) 一个函数

如果您得到一个行TypeError"Blah未定义"或"无法读取undefined的属性foo",则表示您有一个变量或属性具有 undefined ,这是变量的默认值,直到您为其分配某些内容。

这与拥有一个尚未定义的变量并尝试读取其值相反,这将触发ReferenceError

例如,请考虑以下内容:

var foo;
console.log(foo.bar); // "TypeError: Cannot read property 'bar' of undefined"

foo变量存在,但其值为 undefined ,因此尝试从中读取属性会导致错误。

对比一下:

console.log(missing); // "ReferenceError: missing is not defined"

在这里,符号missing没有定义;引擎不知道你在说什么。这通常表示缺少var语句。

旁注:如果你赋值一个你从未声明过的变量(在 ES3 中或在 ES5 中处于"松散"模式),JavaScript 有一个非常令人惊讶的行为:它会创建一个全局变量。我称之为隐式全局的恐怖。这意味着,如果我不是上面console.log(missing);,而是这样做:

missing = "foo";

。我会创建一个新的全局变量,即使该代码在函数中。值得庆幸的是,在 ES5 中,我们可以使用"严格"模式,这使得它一直ReferenceError。:-)

这通常意味着您请求的"事物"不存在(或者至少无法被请求它的函数找到)。这可以是变量、对象或函数。

在你所说的onSearch的情况下,很可能找不到该功能。可能是在文件请求它之后加载了包含该函数的文件(所以onSearch在 b.js 中,请求它的文件在 a.js. a.js 在 b.js 之前在你的<head>中)。因此它尚不存在,因为javascript文件加载线性。

你的问题

问题不在于onSearch是未定义的,而是它使用了一个未定义的变量db

(从现在开始,我将假设qwertyuiopasddsghjdsvjkfhjkl没有声明)

在以下情况下,您会看到未定义的错误:

  • 您使用尚未声明的变量。

    qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
    
  • 在已声明但未定义的变量上使用属性: var a; A.B;类型错误:a 未定义

在以下情况下,变量未定义:

  • (错误)您尚未声明它

    // qwertyuiopasddsghjdsvjkfhjkl is undefined
    qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
    
  • (无错误)您已声明它,但它没有值

    var a; //a is undefined
    
  • (无错误)您将变量分配给void(0)(您可以使用所有内容更改0)或未修改的undefined

    var a = undefined; //a is undefined
    var a = void(0); //a is undefined
    undefined = 'abc';
    var a = undefined; //a is NOT undefined
    

如何检查

如果您不知道变量是否未定义,则可以使用

  • typeof myVar === 'undefined'

    如果出现以下情况,它将返回true

    • 未声明myVar
    • 已声明myVar但未定义

    如果声明了myVar并且myVar未定义,则返回false

  • myVar === void(0)

    如果声明了myVar并且未定义myVar则返回true

    如果声明了myVar并且myVar不是未定义的,则返回false

    如果未声明myVar则会引发错误

  • myVar === undefined

    如果undefined尚未修改,则与myVar === void(0)相同。

  • !myVarif(myVar)

    如果声明了myVar,则返回true

    • myVar未定义
    • myVar是假的(null0false''

    如果声明了myVar并且myVar为真,则返回false

    如果未声明myVar则会引发错误