Вопрос

I want to convert "1,2,3" to [1,2,3]. But there is an exception when converting "" to array. Because I get [""]. That is not valid for my case. So I need to check is it number or String. Let see this in code

function someWayToParse(some_string) {
    var final_product = [];

    var tmp_array = some_string.split(',');

    //if some_string == "" tmp_array will result [""];
    if (tmp_array[0].length===0)
        return [];

    for (var item in tmp_array)
        final_product.push(parseInt(tmp_array[item], 10));

    return final_product;
}

var stringToParse = "1,2,3";

var array_of_ints = someWayToParse(stringToParse);

I am just looking the best way to do this in a function and avoid possible mistakes. Please be memory efficient, for my curiosity's sake.

Это было полезно?

Решение

Smaller code for it would be:

function myConverter(string) {
  if (!string) return [];
  return string.split(',').map(Number);
}

console.log(myConverter('1,2,3'));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top