-1

I'm having trouble updating the score property. I'm fairly new but still feel crazy not being able to figure this out.

'fight' is a string

function alphabetWar(fight) {
  let leftSide = {
    'w': 4,
    'p': 3,
    'b': 2,
    's': 1,
    'score': 0
  }

  let rightSide = {
    'm': 4,
    'q': 3,
    'd': 2,
    'z': 1,
    'score': 0
  }

  for (let char of fight) {
    if (leftSide.hasOwnProperty(char)) {
      leftSide.score += leftSide.char;
      if (rightSide.hasOwnProperty(char)) {
        rightSide.score += rightSide.char;
      }
    }
  }
  console.log(leftSide.score)
  if (leftSide.score === rightSide.score) return "Let's fight again!";
  return leftSide.score > rightSide.score ? 'Left side wins!' : 'Right side wins!';
}
Anand G
  • 3,130
  • 1
  • 22
  • 28
clinzy25
  • 91
  • 8
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+use+variable+as+key+name) of [JavaScript set object key by variable](https://stackoverflow.com/q/11508463/4642212). – Sebastian Simon Feb 19 '21 at 03:11

2 Answers2

0

Bracket notation allows you to access a property of your object with a variable value:

let char = 'm';

rightSide.score += rightSide[char];
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • You're right but that didn't solve the problem. I also tried changing all dot notations to bracket notation – clinzy25 Feb 19 '21 at 13:17
0

You can try:

for (let char of fight.split('')) {
  if(typeof leftSide[char] != 'undefined'){
    leftSide.score += leftSide[char]
  }
  if(typeof rightSide[char] != 'undefined'){
    rightSide.score += rightSide[char]
  }
}
Minh Viet
  • 61
  • 1
  • 5
  • This worked. Could you help me understand why `let char of fight` did not work and `let char of fight.split('')` did? – clinzy25 Feb 19 '21 at 13:20
  • For loops will usually work well with arrays of data types. String in languages ​​like C or C ++ is array of characters, but in javascript it is simply a string – Minh Viet Feb 21 '21 at 05:44
  • .split('') can change from string to array – Minh Viet Feb 21 '21 at 05:49