为什么此代码返回未定义 我找不到原因
function findShort(s){
let splitted = s.split(' ');
let result = splitted[0].length ;
let looped
for (var i=0 ; i++ ; i<splitted.length){
looped = splitted[i].length;
if (looped < result) {return looped}else {return result }}
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
我应该得到最小的单词数
答案 0 :(得分:2)
您的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'));
答案 1 :(得分:0)
您的for循环实现是错误的,应该是:
for (var i=0; i<splitted.length; i++)
答案 2 :(得分:0)
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"));