3 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的for循環(huán)condition并被increment反轉(zhuǎn):
for (var i=0 ; i++ ; i<splitted.length){ ...
相反,應(yīng)為:
for (var i = 0; i < splitted.length; i++) { ...
您還必須修復(fù)循環(huán)代碼,因?yàn)樗鼤?huì)在您內(nèi)部if語(yǔ)句的兩個(gè)分支中返回,這意味著將僅運(yùn)行一次迭代。
如果要返回最小單詞的長(zhǎng)度,請(qǐng)執(zhí)行以下操作:
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貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
令condition和increment 是錯(cuò)誤的,你for loop還有循環(huán)內(nèi)的代碼,
僅當(dāng)您return在所有條件下都具有時(shí),它才會(huì)檢查第一個(gè)元素。
這是正確的
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"));

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
您的for循環(huán)實(shí)現(xiàn)是錯(cuò)誤的,應(yīng)該是:
for (var i=0; i<splitted.length; i++)
添加回答
舉報(bào)