Alice Rosier
Alice Rosier

Reputation: 35

js number function for calculator error

Can anyone explain to me why I get the error message Uncaught ReferenceError: Invalid left-hand side in assignment when I run the below function.

function number(a){
    var last = parseInt(stream.charAt(stream.length-1));
    if(stream === ''){
      stream = a;
    }
    else if(isNumber(last)){
      console.log(last);
      stream.charAt(stream.length-1) = last*10 + a;
    }
    else{
      stream += ' '+a;

    }
    document.getElementById('display').innerHTML = stream;
}

Upvotes: 1

Views: 90

Answers (3)

Mapendra
Mapendra

Reputation: 75

Your problem seems to be this codepart

stream.charAt(stream.length-1) = last*10 + a;

charAt returns a string, and not a position in your stream (i assume that your stream is a string), so you cant overwrite it.

To solve this you could do something like:

 stream = stream.substring(0,stream.length-1)+last*10+a

Im not allowed to comment but Cerbrus answer wont work for last = '0' and will in this case add an additional 0, this should work

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72849

The error is in this line:

stream.charAt(stream.length-1) = last*10 + a;

You can't assign something to stream.charAt(). That function only returns a character.

From what I can gather, you're getting the last character from the stream. If it's a integer, you multiply it by 10, then append a to the stream.

Instead of that, this will give the same result:

stream += '0' + a;

Since you're adding the value back into the array, it really doesn't matter if you multiply a single digit integer with 10, or if you just add a "0" after it.

Upvotes: 5

Akhil
Akhil

Reputation: 95

the problem is that you can't assign like this

 stream.charAt(stream.length-1) = last*10 + a;

Upvotes: -1

Related Questions