3 回答
TA贡献1784条经验 获得超7个赞
正如评论中所建议的那样,因为您只想更好地打印数字用户一个包含数字字符串的数组,并使用该数组中数字的索引位置来创建以字母形式表示您的数字的字符串
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贡献1804条经验 获得超7个赞
对于我的观点:
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 输入区域。
numbers
是包含您的输入的字符串数组。newNumbers
是一个字符串数组,其中包含转换为文字数字的数字。
TA贡献1725条经验 获得超7个赞
我相信这就是您要找的:
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>
添加回答
举报