I have a javascript if-else statement. It gets data from a websocket and depending on the condition being true or false enters the relevant branch.
But what I'm finding is that the data being added to both arrays is the same. This is the code:
cities = JSON.parse(evt.data);
if (cities.tag == 'red'){
dataset.length = 0;
console.log(cities.tag);
for (var i = 0, item; item = buffer[i]; ++i) {
buffer[i][1][0] = cities.clusters[item[0]] || 0;
//console.log(buffer);
dataset.push(buffer[i][1][0]);
console.log('no1: ',dataset);
}
}else{
dataset2.length = 0;
console.log(cities.tag);
for (var i = 0, item; item = buffer2[i]; ++i) {
buffer2[i][1][0] = cities.clusters[item[0]] || 0;
dataset2.push(buffer2[i][1][0]);
console.log('no2: ',dataset2);
}
}
draw();
I know that it enters the correct branch and that the data is different, but somehow the code in the else branch just duplicates the array in the if branch.
I think theres must be something in the code, but I cannot see what.
Thanks
2 Answers 2
Read you code slowly and consider typing:
- For every
itemand indexiof item in buffer:- set
buffer2[i][1][0]to the value ofcities.clusters[item[0]]or0if previous expression is not defined;
- set
but see, there's a problem here already
If every every element at any given level of the buffer is supposed to be the same type, buffer2 is an array of array of arrays.
That means item is an array of arrays, and item[0] is an array, not an element. That, doesn't mean the statement won't work somehow, but, unless you are trying to win some sort of javascript obfuscation contest, that's not good code, and is likely not what was intended.
Edit: That really is a bizarre way of iterating through an array; maybe there exists some reason in this universe to iterate through an array that way, but if your array has any elements that would in some way evaluate to false, it wouldn't even iterate through all the elements.
Comments
Not able to understand your code fully as you have shown partial code. If most of the code is right, suggest swapping the array.push like this:
dataset.push(cities.clusters[item[0]] || 0);
dataset2.push(cities.clusters[item[0]] || 0);
This should work if buffer and buffer2 are not same.
var dataset = [], dataset2 = dataset, that's the reason.