3 回答
TA贡献1872条经验 获得超3个赞
您的for循环condition并被increment反转:
for (var i=0 ; i++ ; i<splitted.length){ ...
相反,应为:
for (var i = 0; i < splitted.length; i++) { ...
您还必须修复循环代码,因为它会在您内部if语句的两个分支中返回,这意味着将仅运行一次迭代。
如果要返回最小单词的长度,请执行以下操作:
function findShort(s) {
let splitted = s.split(' ');
let result = splitted[0].length;
for (let i = 0; i < splitted.length; i++) {
const looped = splitted[i].length;
if (looped < result) {
result = looped;
}
}
return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
或更短一些,使用Array.prototype.reduce():
function findShortest(s) {
return s.split(/\s+/).reduce((out, x) => x.length < out ? x.length : out, s.length);
};
console.log(findShortest('bitcoin take over the world maybe who knows perhaps'));
TA贡献1848条经验 获得超10个赞
令condition和increment 是错误的,你for loop还有循环内的代码,
仅当您return在所有条件下都具有时,它才会检查第一个元素。
这是正确的
function findShort(s) {
let splitted = s.split(' ');
let result = splitted[0].length;
let looped
for (var i = 0; i < splitted.length; i++) {
looped = splitted[i].length;
if (looped < result) { result = looped }
}
return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
添加回答
举报