我想調節我輸入的值(“ello”)和變數(“hello”)的字串。
如果它在 string("hello") 中找到,則回傳值應該是 "ello"。如果未找到,則回傳值應為 -1。
但由于條件(strs[i] == arrayS[tempVal]) ,它回傳了 "llll" 4 次。
我怎樣才能得到上面提到的正確答案?
var stres = "hello";
var strs = [...stres];
function searchStr(s) {
let arrayS = [...s];
let tempVal = 0;
let tempStr = [];
while (tempVal < arrayS.length) {
for (let i = 0; i < strs.length; i ) {
if (strs[i] == arrayS[tempVal]) {
tempStr.push(arrayS[tempVal]);
}
}
tempVal ;
}
return tempStr;
}
const res = searchStr("ello");
console.log('res', res)
uj5u.com熱心網友回復:
根據您的說法,邏輯是正確的,只是在滿足條件時中斷 for 回圈。檢查下面的代碼片段和控制臺輸出。
var stres = "hello";
var strs = [...stres];
function searchStr(s) {
let arrayS = [...s];
let tempVal = 0;
let tempStr = [];
while (tempVal < arrayS.length) {
for (let i = 0; i < strs.length; i ) {
if (strs[i] == arrayS[tempVal]) {
tempStr.push(arrayS[tempVal]);
break;
}
}
tempVal ;
}
return tempStr;
}
const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350517.html
標籤:javascript 算法
下一篇:使陣列不減少的最小操作次數
