Assign operable values to the letters of the alphabet

2

Like this:

a=4 b=2 c=8 ... ... h=6 i=3 ...
var palabra=prompt("di lo que quieras");
Input del usuario: "Hi!"

I do not know how to approach this:

var result= h+i??????
alert(result);

And depending on the string obtained, then add these values.

    
asked by Nian_cat 10.02.2016 в 20:40
source

2 answers

4

There are several ways to solve this problem. I propose you one using the benefits of JavaScript:

var mapa = { "a":4, "b":2, "c":8, "h":6, "i":3 }; //agregar las necesarias
var palabra=prompt("di lo que quieras");
var result = palabra.toLowerCase()
    .split('')
    .map(x => mapa[x] || 0 )
    .reduce( (x, y) => x + y);
alert(result);

Explanation:

  • mapa : map where we can place the characters and their numerical values
  • palabra : name of the variable that stores the text entered by the user.
  • toLowerCase : function to place all characters in lowercase.
  • split('') : will create an array with each character of the text string.
  • map : function that will transform ( map ) the elements of the arrangement when applying the function that we place inside
  • x => mapa[x] || 0 : A lambda is used that is to avoid declaring additional functions in the code, in this way the code is reduced and becomes more readable.
    • x is the argument of the function.
    • => indicates the start of the function.
    • mapa[x] || 0 will get the [x] element that is declared in mapa . This should be a number. If you use an element such as ! that is not on the map, this will return undefined . To transform% co_from% to 0, the artifice undefined is used
  • numero || 0 : function that will reduce all elements of the array. It is used to obtain a single result of all the elements of an array.
  • reduce : A lambda that receives two arguments and returns the sum of them.
answered by 10.02.2016 / 20:45
source
1

NOTE > > See the answer of @LuiggiMendoza that uses some newer features of JavaScript, this version is for previous browsers.

Suppose you can put the values in an object instead of independent variables:

var diccionario = { a:1, b:2, c:8, h:6, i:3 };

var input = "hi"; // agrega aqui el prompt

var resultado = 0;

for(var i in input) {
  var c = input.charAt(i);
  if (c in diccionario) {
    resultado += diccionario[c]
  }
}

alert(resultado);

Then for each character in your entry, you take the value of the "map" of values and the sums in a loop.

    
answered by 10.02.2016 в 20:48