3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
正如評(píng)論中所建議的那樣,因?yàn)槟幌敫玫卮蛴?shù)字用戶一個(gè)包含數(shù)字字符串的數(shù)組,并使用該數(shù)組中數(shù)字的索引位置來創(chuàng)建以字母形式表示您的數(shù)字的字符串
var numtoStrarr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
function returnNumberAsString(numberInput) {
var numSplit = numberInput.toString().split('');
var stringArr = [];
numSplit.forEach(x => stringArr.push(numtoStrarr[x]));
return stringArr.join(' ');
}
console.log(returnNumberAsString(100));
console.log(returnNumberAsString(1130));

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
對(duì)于我的觀點(diǎn):
const output = document.getElementById("numbersOutput");
function replaceNumber(input) {
const numbersInLetters = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let numbers = input.value.split("");
let newNumbers = numbers.map((n) => numbersInLetters[parseInt(n)]);
output.innerHTML = newNumbers.join(" ");
}
<input type="number" placeholder="Enter a number" onkeyup="replaceNumber(this)" />
<p id="numbersOutput"></p>
您仍然使用您的 HTML 輸入?yún)^(qū)域。
numbers
是包含您的輸入的字符串?dāng)?shù)組。newNumbers
是一個(gè)字符串?dāng)?shù)組,其中包含轉(zhuǎn)換為文字?jǐn)?shù)字的數(shù)字。

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
我相信這就是您要找的:
const numberToWordsBank = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
const numberInput = document.getElementById("number-input");
const words = document.getElementById("words")
const updateTranslation = document.getElementById("update-translation")
updateTranslation.addEventListener("click", () => {
words.textContent = '';
for (const number of numberInput.value) {
words.textContent += numberToWordsBank[number] + ' ';
}
});
HTML(將 script.js 更改為您的 javascript 文件的名稱):
<input id="number-input" type="text" />
<button id="update-translation">update</button>
<p id="words"></p>
<script src="script.js"></script>
添加回答
舉報(bào)