gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'length' of undefined | Finding the shortest word in a string | Codewars Challenge

转载 作者:行者123 更新时间:2023-11-30 14:22:14 24 4
gpt4 key购买 nike

我目前正在尝试创建一个函数来查找一串单词中最短的单词。

问题:我收到以下错误

类型错误:无法读取未定义的属性“长度” 在找短 在 Test.describe._ 在/runner/frameworks/javascript/cw-2.js:152:11 在 Promise._execute 在 Promise._resolveFromExecutor 在新的 promise 在 Object.describe 在/home/codewarrior/index.js:24:10 在/home/codewarrior/index.js:28:5 在 Object.handleError

这是我的代码

findShort("turns out random test cases are easier than writing out basic ones");

function findShort(s){

let array = s.split(" ");
let shortestWord = array[0];

for (i = 0; i < array.length; i++) {
let str = array[i + 1];

if (shortestWord.length > str.length) {
shortestWord = str.length;
}

}

return shortestWord;
}

最佳答案

我看到两个问题:

  • let str = array[i + 1]将导致 undefined在循环的最后一次运行时。那是因为在最后一次运行中,i比数组长度小一,所以 i + 1因此超出了数组边界。为了弥补这一点,考虑将循环条件更改为 i < array.length - 1 .

  • 其次,您将字长分配给 shortestWord变量,我认为你的意思是将单词本身分配给它。

考虑到这两个变化,您可以像这样修改您的代码:

function findShort(s) {

let array = s.split(" ");
let shortestWord = array[0];

for (i = 0; i < array.length - 1; i++) { // -1 here to compensate for the +1 on the next line.
let str = array[i + 1];

if (shortestWord.length > str.length) {
shortestWord = str; // Just assign the word itself to this variable, not the length of it.
}

}

return shortestWord;
}

const result = findShort("turns out random test cases are easier than writing out basic ones");
console.log(result);

关于javascript - 类型错误 : Cannot read property 'length' of undefined | Finding the shortest word in a string | Codewars Challenge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52562016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com