我正在嘗試學習 forEach() 方法,但找不到更高級的示例。所以我考慮重構我的 Codewars 代碼以從中學習。我不知道在嵌套回圈中正確使用 forEach 方法。希望你能幫助我從這個例子中學習:)
6 kyu - 替換為字母位置 https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript
function alphabetPosition(text) {
let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
let pointsHolder = []; //empty array for score
for (let i = 0; i < textToArray.length; i ){
for (let j = 0; j < alphabet.length; j ) {
if (textToArray[i] == alphabet[j] ) { //We check the index of given string letter in alphabet
pointsHolder.push(j 1) //give it a score based on place in alphabet( 1 for 0 as 1st index)
}
}
}
return pointsHolder.join(' '); //return scored array as a string with spaces
}
uj5u.com熱心網友回復:
確實沒有必要使用計算量大的嵌套回圈。這樣,您也不必手動創建 AZ 陣列。
您可以使用 . 輕松地將字母轉換為任意數字String.charCodeAt()。a字符代碼為 97,b字符代碼為 98,等等...要獲得從 1 開始的索引(a=1,b=2,...),您只需從數字中減去 96。
function alphabetPosition(text) {
const alphabets = text.toLowerCase().replace(/[^a-z]/g, '').split('');
return alphabets.map(alphabet => alphabet.charCodeAt(0) - 96).join(' ');
}
或者,您也可以使用for...of回圈,但這需要在回傳之前將陣列存盤在另一個變數中:
function alphabetPosition(text) {
const alphabets = text.toLowerCase().replace(/[^a-z]/g, '');
const codes = [];
for (const alphabet of alphabets) {
codes.push(alphabet.charCodeAt() - 96);
}
return codes.join(' ');
}
uj5u.com熱心網友回復:
(注意:@Terry 的解決方案仍然是解決您的代碼挑戰的更有效的解決方案)
您可以通過以下方式替換它:
function alphabetPosition(text) {
let textToArray = text.replace(/[^a-zA-Z]/gi, '').toUpperCase().split('');
const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
let pointsHolder = [];
textToArray.forEach(t2a => {
alphabet.forEach((a, j) => {
if (t2a == a) { pointsHolder.push(j 1) }
})
})
return pointsHolder.join(' ');
}
console.log(alphabetPosition("ABCSTU"))
uj5u.com熱心網友回復:
Terry's answercharCode中提出的解決方案的替代方案,但也避免了嵌套回圈,是創建一個您想要得分的字符,然后從傳遞的字串中按字符訪問它。Map
請記住,字串是可迭代的,無需轉換為陣列。
function alphabetPosition(text) {
text = text.toUpperCase().replace(/[^A-Z]/gi, '');
const alphabet = new Map(
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
.map((v, i) => [v, i 1])
);
const pointsHolder = [];
for (const char of text) {
pointsHolder.push(alphabet.get(char))
}
return pointsHolder.join(' ');
}
console.log(alphabetPosition("AB??CS??TU"))
這也允許您使用不一定具有連續字符代碼的 Map
function alphabetPosition(text) {
text = text.toUpperCase().replace(/[^??????]/gi, '');
const alphabet = new Map(
["??", "??", "??"]
.map((v, i) => [v, i 1])
);
const pointsHolder = [];
for (const char of text) {
pointsHolder.push(alphabet.get(char))
}
return pointsHolder.join(' ');
}
console.log(alphabetPosition("AB??CS??TU"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424474.html
標籤:javascript 数组 功能 循环
