There is a code:

var test = prompt("введите число от одного до трех"); if (test == 1) alert("один"); if (test == 2) alert("два"); if (test == 3) alert("три"); 

Is it possible to replace it with the substitution of the desired text instead of a call, and that is something like this:

 var test = prompt("введите число от одного до трех"); alert(if(test == 1){"один"};if(test == 2){"два"};if(test == 3){"три"};); 

that is, you need to set the text instead of calling the function with the desired parameter.

    3 answers 3

     var test = prompt("введите число от одного до трех"); console.log({1:"один",2:"два",3:"три"}[test]); // или так: console.log(["один","два","три"][test-1]); 

    • thanks, exhaustive answer - perfect

    Perhaps, but for me it is better to create a variable and switch / case ...

     var test = prompt("введите число от одного до трех"); alert(test == 1?"один":test==2?"два":"три"); 

      You can simplify. Take out the word by number in a separate function. Instead of conditions, use a constant with a hash of numbers and words. Like this:

       function wordFromNumber(number) { const WORDS = { 1: "one", 2: "two", 3: "three"}; return WORDS[number]; } var number = prompt("Type a number from 1 to 3"); if (wordFromNumber(number) != undefined) { alert(wordFromNumber(number)); } 

      Jsfiddle working example

      Also in the code I added a condition. If there is no associated word, do not show alert .

      • and then what is the meaning of a separate function? each time you call the same object to create? - Grundy
      • reuseability - Vitaly Emelyantsev
      • one
        oh well, it's much easier to remove the function and make a global object, it's better than the global function :-) - Grundy