2

I am facing a problem with a web application I am making.

I am using node.js for backend and the server is sending (using socket.io) a string like this "0010000110�0".

On the client side I have:

$(document).on("pageinit", function(){

var socket = io.connect('http://localhost:8080');
var tmpData = [];

socket.on('recData', function(data){
    tmpData = data; //here I put the received string in the tmpData array
});

//checking for the string array state
$("#deskLight-1").on("vclick", function(){
        if(tmpData[2] == '1'){
            tmpData[2] = '0';
            alert(tmpData);
        }   
        else if(tmpData[2] == '0'){
            tmpData[2]='1';
            alert(tmpData);
        }   
    });

});

So the idea is to turn on/off the light. This is just part of the code, so lets focus on the tmpData[2] only.

The if condition works correctly and the alert dialog shows only the old tmpData string (so this one 0010000110�0). And it should be changed to this 00**0**0000110�0

I dont understand why tmpData[2] = '0' or tmpData[2] = '1' doesn't update the indexed value. Any ideas?

captainsac
  • 2,484
  • 3
  • 27
  • 48
  • You can try once with `tmpData = data.split('')` and then `alert(tmpData.join(''))` – Satpal May 18 '15 at 09:23
  • Strings in JavaScript are immutable, so to change something in string you have to create new one. Something like [this question](http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript). – Regent May 18 '15 at 09:24

1 Answers1

1

Strings in JavaScript are immutable:

var str = '123';
str[1] = 'x';
console.log(str); // '123'

You seem to want to use your data as an array of characters, so store it as an array:

socket.on('recData', function(data){
    tmpData = data.split(''); // array of characters
});

Remember to join the characters together if you need the (updated) string back:

console.log(tmpData.join(''));
Tibos
  • 27,507
  • 4
  • 50
  • 64