Assign operable values to letters of the alphabet

Like this:

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

I don't know how to approach this:

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

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

 2
Author: Nian_cat, 2016-02-10

2 answers

There are several ways to solve this problem. I propose one using the goodness 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 in the string text.
  • map: function that will transform (map) the elements of the array by applying the function we place inside
  • x => mapa[x] || 0: a lambda is used which is to avoid declaring additional functions in the code, 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 element [x] that is declared in mapa. This should be a number. If an element like ! is used that is not on the map, this will return undefined. To transform undefined to 0 the artifice numero || 0
  • reduce: function that will reduce all elements of the array. It is used to obtain a single result of all elements of an array.
  • (x,y) => x + y: a lambda that receives two arguments and returns the sum of them.
 5
Author: , 2016-02-10 19:50:38

Note > > Check out @LuiggiMendoza's answer that uses some newer JavaScript features, this version is for older 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 input, you take the value from the" map " of values and sum them in a loop.

 1
Author: rnrneverdies, 2016-02-10 19:48:58