Charlie
Charlie

Reputation: 11777

Assign a letter a numerical value in JS?

Is it possible to assign a certain amount of letters a numerical value, that can later be added together?

Ex:

A,B,C = 1
D,E,F = 2

So that if I add A + D + D I get 5?

I would post what I tried, but I don't even know what I could try in this sitation.

Upvotes: 0

Views: 3009

Answers (3)

zerkms
zerkms

Reputation: 254916

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    letters = alphabet.split(''),
    len = letters.length,
    i;

for (i = 0; i < len; i++) {
    window[letters[i]] = Math.ceil((i + 1) / 3);
}

alert(D + D + A);

http://jsfiddle.net/zerkms/dKQS2/

Upvotes: 3

xdazz
xdazz

Reputation: 160833

You need to do

A = B = C = 1;
D = E = F = 2;

Upvotes: 6

McGarnagle
McGarnagle

Reputation: 102743

You could use a property map to assign the values:

var map = { A:1, B:1, C:1, D:2, E:2, F:2 };
console.log(map.A+map.D+map.D);

5

Upvotes: 3

Related Questions