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);