我是 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] 删除。
我来说两句