如果有人可以指出或只是提供線索我做錯了什么,將不勝感激。所以任務是:
給定 2 個字串 a 和 b,回傳它們包含相同長度 2 子字串的位置數。所以 "xxcaazz" 和 "xxbaaz" 產生 3,因為 "xx"、"xx"、"aa" 和 "az" 子字串出現在兩個字串的相同位置。
function('xxcaazz', 'xxbaaz') 應該回傳 3
function('abc', 'abc') 應該回傳 2
function('abc', 'axc') 應該回傳 0
我的代碼:
function stringMatch(a, b){
// convert both strings to arrays with split method
let arrA = a.split("")
let arrB = b.split("")
// create 2 empty arrays to feel in with symbol combinations
let arrOne = [];
let arrTwo = [];
// loop through the first array arrA and push elements to empty arrayOne
for ( let i = 0; i < arrA.length ; i ) {
arrOne.push(arrA[i] arrA[i 1])
}
// loop through the first array arrB and push elements to empty arrayTwo
for ( let i = 0; i < arrB.length ; i ) {
arrTwo.push(arrB[i] arrB[i 1])
}
// create a new array of the matching elements from arrOne and arrTwo
let newArray = arrOne.filter(value => arrTwo.includes(value))
// return the length 0f the newArray - that's supposed to be the answer
return newArray.length
}
感謝幫助!
uj5u.com熱心網友回復:
在回圈的最后一次迭代中,不會有“下一個”字符,arrB[i 1]將是未定義的。解決這個問題的最簡單方法是只回圈到倒數第二個字符,或直到i < arrB.length - 1.
for ( let i = 0; i < arrB.length - 1; i ) {
arrTwo.push(arrB[i] arrB[i 1])
}
例如..
console.log(stringMatch('xxcaazz', 'xxbaaz')); //should return 3
console.log(stringMatch('abc', 'abc')); // should return 2
console.log(stringMatch('abc', 'axc')); //should return 0
function stringMatch(a, b){
// convert both strings to arrays with split method
let arrA = a.split("")
let arrB = b.split("")
// create 2 empty arrays to feel in with symbol combinations
let arrOne = [];
let arrTwo = [];
// loop through the first array arrA and push elements to empty arrayOne
for ( let i = 0; i < arrA.length -1 ; i ) {
arrOne.push(arrA[i] arrA[i 1])
}
// loop through the first array arrB and push elements to empty arrayTwo
for ( let i = 0; i < arrB.length - 1; i ) {
arrTwo.push(arrB[i] arrB[i 1])
}
// create a new array of the matching elements from arrOne and arrTwo
let newArray = arrOne.filter(value => arrTwo.includes(value))
// return the length 0f the newArray - that's supposed to be the answer
return newArray.length
}
作為獎勵,這是我自己的解決方案......
console.log(stringMatch('xxcaazz', 'xxbaaz')); //should return 3
console.log(stringMatch('abc', 'abc')); // should return 2
console.log(stringMatch('abc', 'axc')); //should return 0
function stringMatch(a, b){
var matches = 0;
for(let i=a.length-1; i--;){
let s1 = a.substring(i, i 2);
let s2 = b.substring(i, i 2);
if(s1 == s2) matches ;
}
return matches;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397312.html
標籤:javascript 数组 细绳 方法
