【问题标题】:JavaScript TypeError: Cannot read property 'eat' of UndefinedJavaScript TypeError:无法读取未定义的属性“吃”
【发布时间】:2017-01-24 20:16:26
【问题描述】:

我正在开展一个项目,以解决在许多报纸上发现的经典“混词”难题。该项目的基本思想是它接受一个打乱的单词(没有空格或特殊字符),生成单词的每个排列,根据我的教授提供的“字典”检查每个排列,然后添加实际上是英语的每个排列word 到一个数组,然后进一步处理以得出结果。

目前,当我尝试检查排列是否在“字典”中时,我遇到了一个问题。下面的代码由我的教授提供,并从外部文本文件创建一个“字典”。根据他的说法,dictionary[w] 应该返回一个与表示单词频率的单词配对的数字,如果该单词不在字典中,则返回“未定义”。

function readDictionary() {
    /**
     * @type {string[]}
     */
    const lines = fs.readFileSync("count_1w.txt", "utf-8").split("\n");
    var line;
    const dictionary = {};
    for (line of lines) {
        line = line.trim();
        let array = line.split('\t');
        if (array.length > 1) {
            let word = array[0];
            let count = array[1];
            if (lexicon[word]) {
                dictionary[word] = parseFloat(count);
            }
        }
    }  
    return Object.freeze(dictionary); 
}

function getDictionary() {
    if (dictionary === null) {
        dictionary = readDictionary();
    }
    return dictionary;
}

var dictionary = getDictionary();

如果dictionary[letters] 不是未定义的,我编写的以下代码应返回“true”...

function inDict(letters) {
     if (dictionary[letters] !== undefined){
         return true;
     }
     else{
         return false;
     }
}

...但是在当前状态下,它会在这篇文章的标题中抛出 TypeError,其中 'eat' 是生成的输入的第一个排列。请注意,在我的实际代码中,readDictionary()、getDictionary() 和 var dictionary = getDictionary 都在 inDict() 上方声明。

如果需要更多详细信息,请随时询问。我对 JavaScript 的个人知识已经到了尽头,多次谷歌搜索都没有发现对我的特定情况有帮助。非常感谢任何建议或意见!

【问题讨论】:

  • 变量类型 != 'undefined'
  • 或者只是return letters in dictionary

标签: javascript undefined typeerror


【解决方案1】:

错误信息很清楚:dictionary 的值是 undefined,这是为什么呢?

问题在于函数getDictionary返回undefined。条件dictionary === null 永远不会是true,因为dictionary 的初始值是undefined,而undefined === nullfalse

所以你真正在做的是

var dictionary; // initial value is undefined
dictionary = dictionary;

什么都不做。

我根本不明白你为什么需要getDictionary。直接初始化dictionary即可:

var dictionary = readDictionary();

您也可以:

null 初始化dictionary(但你为什么要这样做?)

var dictionary = null;
dictionary = getDictionary();

改为与undefined 比较:

function getDictionary() {
    if (dictionary === undefined) {
        dictionary = readDictionary();
    }
    return dictionary;
}

总体而言,getDictionary 设计不佳,因为它隐含依赖于dictionary,但也返回一个值。

【讨论】:

  • 似乎已经做到了。好像我的教授为这个项目提供了损坏的代码。感谢您的帮助。
猜你喜欢
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多