-1

I am facing a problem with this issue

this is the question

enter image description here

This is my solution

let whigt = {
  A: 1,
  B: 2,
  C: 3,
  D: 1,
  E: 2,
  F: 3,
  G: 1,
  H: 2,
  I: 3,
  J: 1,
  K: 2,
  L: 3,
  M: 1,
  N: 2,
  O: 3,
  P: 1,
  Q: 2,
  R: 3,
  S: 4,
  T: 1,
  U: 2,
  V: 3,
  W: 1,
  X: 2,
  Y: 3,
  Z: 4
}

let charwhigt = 0;

function presses(phrase) {
  let arraychar = phrase.toUpperCase().split("");
  arraychar.map((el) => {
    console.log(whigt.el)

  })
}

presses("omar")

I'm trying to link the object key to the letter, but when I print the object's value, it gives me the output NAN

What is my mistake did and what is the solution to make the solution right؟؟

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34

1 Answers1

0

Your code try to search el into whigt instead use [el] will search value of el

let whigt = {
  A: 1,
  B: 2,
  C: 3,
  D: 1,
  E: 2,
  F: 3,
  G: 1,
  H: 2,
  I: 3,
  J: 1,
  K: 2,
  L: 3,
  M: 1,
  N: 2,
  O: 3,
  P: 1,
  Q: 2,
  R: 3,
  S: 4,
  T: 1,
  U: 2,
  V: 3,
  W: 1,
  X: 2,
  Y: 3,
  Z: 4
}

let charwhigt = 0;

function presses(phrase) {
  let arraychar = phrase.toUpperCase().split("");
  arraychar.forEach((el) => {    
    console.log(whigt[el]);
  });
}

presses("omar");

PS: i prefer use forEach for loop array, see the differente here

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
  • Thank you, it works, but I have a question What I know is that when I want to access the value of the object, I use the name of the object and then it's key And my whigt is an Object. Why do I use the [ ] to search within an Object? –  Nov 15 '21 at 10:24
  • 1
    When you say ```whigt.el```, you are trying to access a property called ```el``` on the object ```whigt```, however ```whigt``` doesn't have that property. You need to do ```whigt[el]``` so that it you can use the variable ```el``` to dynamically access the property. – chai Nov 15 '21 at 10:29
  • But when I try to access the object value outside the map, it gives me the value correctly look at this whigt.A // 1 whigt .B//2 –  Nov 15 '21 at 10:36
  • Also when I try to print whigt.KEY directly inside the map, it gives me the value correctly –  Nov 15 '21 at 10:38
  • 1
    yes it works because you specify the key for example `whigt.A` but if you use `whigt.el` it is as if in the `object` you are looking for the key `el` which obviously is not there – Simone Rossaini Nov 15 '21 at 10:43