0

I am currently learning JS but I thought I'd give it a shot and create this conversion. I don't know what I am doing wrong and I'd appreciate if anyone can guide me.

    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);
}
amir
  • 11
  • 7
  • What are you trying to do, and what is it actually doing that is incorrect? What are you entering as input, and what is the expected result? –  Apr 01 '21 at 14:07
  • Basically put a number which outputs it in text. So, 1 will give one and so on... I dont know what else to do to achieve that. I'm new to JS – amir Apr 01 '21 at 14:10

2 Answers2

1

I believe this is what you are looking for. Simply use bracket notation to get the array item you are looking for by index.

const wordifyNum = num => ["Zero", "One", "Two", "Three", "Four"][num];

wordifyNum(0); // -> "Zero"
wordifyNum(1); // -> "One"
wordifyNum(2); // -> "Two"
wordifyNum(3); // -> "Three"
wordifyNum(4); // -> "Four"

For a more robust example that works all the way up to 999 dynamically, check out wordify.js by Nina Scholz.

Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
  • What do i do after that ? I'm confused – amir Apr 02 '21 at 11:56
  • This works as is. This function converts and returns the desired number as a word. In order to log its result to the console, do this: `console.log(wordifyNum(4))`, which will log `"four"` to the console. Just add as many number words as you need to support in your program. – Brandon McConnell Apr 02 '21 at 13:13
0

You are close, but put yourself in the wrong direction

const a = lNumbers.indexOf("Zero");

This is incorrect: Why would you want to know the position of a hardcoded string 'Zero'?

Instead, you want to use the value of box and access the lNumbers by key. You can see this answer and then the 2nd codeblock1. They use a hardcoded "fruit", but you have something else to put there ;)

1 Actually, the forth is what you are looking for, but because the variable name and its value are the same, it could be a little confusing

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • i dont understand what you mean by the value of box? Your solution is a little confusing to me – amir Apr 01 '21 at 14:40
  • 1
    @amir You have a variable called `box`. It contains a value. –  Apr 01 '21 at 15:33