简体   繁体   中英

Invalid Javascript left hand side in assignment

Wondering why I'm getting invalid left hand side assignment. Doesn't my for loop iterate through the array of string characters, get its numeric value (ASCII) and add it to count and re-assign it to the variable?

function getCharNumber(string1, string2) {
  let count1 = 0
  let count2 = 0
  let strArray1 = string1.split('')
  let strArray2 = string2.split('')
  for (let i = 0; i < strArray1.length; i++) {
    strArray1[i].charCodeAt(0) += count1
  }
  for (let i = 0; i <strArray2.length; i++) {
    strArray2[i].charCodeAt(0) += count2
  }
  console.log(count1, count2)
}

Reverse the order at call to String.prototype.charCodeAt() . Assign the result of the call to count1 , count2

for (let i = 0; i < strArray1.length; i++) {
    count1 += strArray1[i].charCodeAt(0);
}
for (let i = 0; i <strArray2.length; i++) {
    count2 += strArray2[i].charCodeAt(0);
}

You're getting an error, like others have stated, because you're trying to assign a value to a number.

strArray1[i].charCodeAt(0) += count1

is functionally equivalent to

12 += count1

That doesn't work b/c you can't assign anything to the number 12 . Instead, you need to increment directly

strArray1[i] =  String.fromCharCode(strArray1[i].charCodeAt(0) + count1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM