How do you iterate through an array of bytes like:
var data = new Buffer("0A0B0C0D", "hex");
for (var i = 0; i < data.length; i++) {
console.log( data[i] ); // will iterate 1 by 1. Not what I wanted
console.log( data[i+=1] ); // tried
console.log( data[(i+=1)-1] ); // tried
}
I just want to iterate through it and get results like: 0A 0C and 0B 0D.
How can I do both of this?
Is a for loop okay? Should I use something else? Any suggestion for better performance are also welcome.
update
I forgot to say that I have to do the actual i++ because I have to go through each byte, but I also want to be able to access the index for the buffer by twos.
So all I need is if the i is 0 then I need to get the data[i].
If the i is 2 then I need to get the data[i+1]. So on and so forth.
This should do it.
for (var i = 0; i < data.length; i+=2)
Your other attempts didn't actually change the value of i. They just told the pointer to look in a different place.
EDIT: Try this:
var data = new Buffer("0A0B0C0D", "hex");
var xx=0;
for (var i = 0; i < data.length; i++) {
console.log( data[i] ); // will iterate 1 by 1. Not what I wanted
console.log( data[xx] );
xx++;
console.log( data[xx] );
xx=0;
}
Although, I don't exactly see how that's going to help. That will just check xx and xx+1 for however many times i is run. If you wanted to check i, and i+1 at the same time, then start anew with i+2, the original answer I gave should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With