Convert array that turned string into array again

0

I use this function to transform words into bytes,

function bytesFromWords (string) {
    var bytes = [];
    for(var i = 0; i < string.length; i++) {
        var char = string.charCodeAt(i);
        bytes.push(char >>> 8);
        bytes.push(char & 0xFF);
    }
    return bytes;
}

If I use it like this, turning the end result into string how can I make it return to an array again?

bytesFromWords('teste soPT').toString();
    
asked by anonymous 20.04.2015 / 16:25

2 answers

5

Use the split() command together with the for()

var string = bytesFromWords('teste soPT');

array_novo=[];
array_splitado=string.toString().split(',');
for(i=0;i<array_splitado.length;i++)
{
   array_novo.push(parseInt(array_splitado[i]));
}
console.log(array_novo);

Living Example

    
20.04.2015 / 16:29
3

You can first use split to transform the list into array, and then a map to generate a new array by transforming each string into a number:

function bytesFromWords (string) {
    var bytes = [];
    for(var i = 0; i < string.length; i++) {
        var char = string.charCodeAt(i);
        bytes.push(char >>> 8);
        bytes.push(char & 0xFF);
    }
    return bytes;
}

var lista = bytesFromWords('teste soPT').toString();
var strArray = lista.split(',');
var numArray = strArray.map(function(item) {
  return parseInt(item, 10);
});
console.log(numArray);

It would be much prettier if you could var numArray = lista.split(',').map(parseInt) . However, map passes the index of the element as the second parameter, while parseInt receives the conversion base as the second parameter, which spoils the result. To make this syntax possible, you would need to create a function that would do parseInt with the second fixed argument:

function myParseInt(num) {
    return parseInt(num, 10);
}
// Aí sim:
var numArray = lista.split(',').map(myParseInt);
    
20.04.2015 / 17:01