我覺得我的解決方案太復雜了。如果有人能推薦一個更簡單的,那就太好了。
這是編碼蝙蝠的挑戰。任務是:
給定一個字串,回傳一個由索引 0,1,4,5,8,9 處的字符組成的字串......所以“kittens”產生“kien”。
例子
altPairs('kitten') → kien altPairs('Chocolate') → Chole altPairs('CodingHorror') → Congrr
我的解決方案(作業正常,但似乎太業余了):
function altPairs(str) {
// convert the string to an Array
let newArr = str.split("")
// create two emtpy Arrays to fill in with the characters of certain indexes from original Array
// myArrOne will contain indexes 0,4,8...
let myArrOne = [];
// myArrTwo will contain indexes 1,5,9...
let myArrTwo = [];
// Loop through the original Array 2 times to push elements into myArrOne and myArrTwo
for (let i = 0; i < newArr.length; i = 4) {
myArrOne.push(newArr[i])
}
for (let i = 1; i < newArr.length; i = 4) {
myArrTwo.push(newArr[i])
}
// create new Array. Loop through myArrTwo and myArrOne and push element to myArrtThree
let myArrThree =[];
for (let i = 0; i <= myArrOne.length && i <= myArrTwo.length; i ){
myArrThree.push(myArrOne[i], myArrTwo[i])
}
// myArrThree to a new string with join method
let myString = myArrThree.join('')
return myString
}
uj5u.com熱心網友回復:
一種簡潔的方法是使用正則運算式:匹配并捕獲 2 個字符,然后匹配最多 2 個字符,并替換為 2 個捕獲的字符。替換所有字串。
const altPairs = str => str.replace(
/(..).{0,2}/g,
'$1'
);
console.log(altPairs('kitten'))// → kien
console.log(altPairs('Chocolate'))// → Chole
console.log(altPairs('CodingHorror'))// → Congrr
(..)- 匹配并捕獲 2 個字符(第一個捕獲組).{0,2}- 匹配零到兩個字符
替換為$1替換為第一個捕獲組的內容。
uj5u.com熱心網友回復:
此解決方案在一次迭代中選擇所有字符。
const altPairs = str => {
let result = '';
for(let i = 0; i < str.length; i = 4){
result = str.substring(i, Math.min(str.length, i 2));
}
return result;
};
console.log( altPairs('kitten') );
console.log( altPairs('Chocolate') );
console.log( altPairs('CodingHorror') );
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399288.html
標籤:javascript 数组 细绳
上一篇:在r中提取分號之間的字符
