我目前正在学习 JS,但我想我会试一试并创建此转换。我不知道我做错了什么,如果有人可以指导我,我将不胜感激。
const box = prompt('Enter Number');
function numberName(n){
const lNumbers = ["","Zero",'One', 'Two', 'Three', 'Four', 'Five']
if (n==0){
const a = lNumbers.indexOf("Zero");
console.log(a);
}
答案 0 :(得分:0)
你很接近,但把自己放在错误的方向
const a = lNumbers.indexOf("Zero");
这是不正确的:您为什么要知道硬编码字符串“零”的位置?
相反,您希望使用 box
的值并通过键访问 lNumbers。您可以看到 this answer and then the 2nd codeblock1。他们使用硬编码的 "fruit"
,但您还有其他东西要放在那里 ;)
1 其实,第四就是你要找的,但是因为变量名和它的值是一样的,所以可能有点混乱
答案 1 :(得分:0)
我相信这就是您要找的。只需使用括号表示法即可通过索引获取您要查找的数组项。
const wordifyNum = num => ["Zero", "One", "Two", "Three", "Four"][num];
wordifyNum(0); // -> "Zero"
wordifyNum(1); // -> "One"
wordifyNum(2); // -> "Two"
wordifyNum(3); // -> "Three"
wordifyNum(4); // -> "Four"
有关一个更强大的示例,该示例可以一直动态运行到 999,请查看 Nina Scholz 的 wordify.js。