为什么我会收到未捕获的类型错误:如果声明了 var,则无法读取未定义的属性“长度”?

安德烈D_

我是 JavaScript 的初学者,最近我正在学习一本书。我正在尝试修改这本书中的一个脚本,该脚本传递一个数字,即单词中的字母数,并输出通过打乱字母获得的单词组合数。虽然原始脚本允许您传递我想要修改的数字,并允许用户输入一个单词,但通过打乱字母返回单词数。我的问题是,当我运行代码时,我不断收到此错误:

未捕获的类型错误:无法在 thingamajig 读取未定义的属性“长度”

为什么会这样?

var word = prompt('Word here.');

function thingamajig(word) {
    var facky = 1;
    clunkCounter = 0; //reset the clunkcounter
    if (word.length == 0) {
        display("clank");
    } else if (word.length == 1) {
        display("thunk");
    } else {
        while (word.length > 1) {
            facky = facky * word.length; //multiply facky with size until size is 0. Basically it is caulculating a factorial
            word.length = word.length - 1;
        }
        clunk(facky);
    }
}

function clunk(times) {
    var num = times;
    while (num > 0) {
        display("clunk"); //keep calling display f until it is = 0
        num = num - 1;
    }
}

function display(output) {
    console.log(output);
    clunkCounter = clunkCounter + 1; //How many times the clunck f called the display f?
}

thingamajig();
console.log(clunkCounter);
安吉特·阿加瓦尔

由于您没有在thingamajig()函数中传递参数,您可以通过更改第一个 if 条件来检查!word而不是word的长度来解决这个问题if (!word)

看起来像这样的东西:

if (!word) {
  display("clank");
} else if (word.length == 1) {
  display("thunk");
} else {
  while (word.length > 1) {
    facky = facky * word.length; //multiply facky with size until size is 0. Basically it is caulculating a factorial
    word.length = word.length - 1;
  }
  clunk(facky);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

的NodeJS - >错误无法读取未定义的属性“长度”

我对长度有疑问。错误TypeError:无法读取未定义的属性“长度”

为什么我会收到TypeError:即使我的Web元素引用正确,也无法读取未定义错误的属性“ getText”?

无法读取未定义Javascript的“长度”类型的属性

无法读取未定义的属性“长度”-JavaScript中的错误

未捕获的TypeError:如果跨度文本为空,则无法读取未定义的属性“ innerHTML”

我为什么会收到此错误:Uncaught TypeError:无法读取未定义的属性“ john”

为什么我会遇到未捕获的TypeError:无法在此处读取未定义的属性“样式”

jQuery错误未捕获的类型错误:无法读取未定义的属性“长度”

未捕获的TypeError:无法读取未定义的属性“长度”(…)

为什么我会收到Uncaught TypeError:无法在分配时读取未定义的属性“ 0”?

javascript错误无法读取未定义的属性“长度”

opencv - 类型错误:无法读取未定义的属性“长度”

为什么我收到错误“未捕获的类型错误:无法读取 HTMLLIElement 处未定义的属性‘样式’。”?

错误错误:无法读取未定义的属性“长度”

未捕获的类型错误:无法读取未定义的属性“长度” - jQuery

未捕获的类型错误:无法读取 jQuery $.each 和 JSON 中未定义的属性“长度”

未捕获的类型错误:无法读取未定义的属性“长度”

Sequelize 创建错误:无法读取未定义的属性“长度”

获取错误:无法读取未定义的属性“长度”

为什么会出错?未捕获的类型错误:无法读取未定义的属性“函数”

VUE:未捕获的类型错误:无法读取未定义的属性“长度”

收到此错误:无法读取未定义的属性“长度”

查找未捕获的类型错误:无法读取未定义的属性“长度”

为什么我会收到此“主页未定义无未定义”错误

为什么我收到错误:类型错误:无法读取未定义的“拆分”的属性

为什么我会收到 TypeError:无法读取未定义的 react-router-dom 的属性“push”

为什么我会收到“类型错误:无法读取未定义的属性‘发送’”?

Javascript 错误:未捕获的类型错误:无法读取未定义的属性“长度”