Convert array of string javascript to array of integer javascript

ε祈祈猫儿з 提交于 2019-12-22 19:26:05

问题


I have an array,

var array = ["1","2","3","4","5"];

then I need to convert to

var array = [1,2,3,4,5];

How can i convert?


回答1:


Map it to the Number function:

var array = ["1", "2", "3", "4", "5"];
array = array.map(Number);
array; // [1, 2, 3, 4, 5]



回答2:


The map() method creates a new array with the results of calling a provided function on every element in this array.

The unary + acts more like parseFloat since it also accepts decimals.

Refer this

Try this snippet:

var array = ["1", "2", "3", "4", "5"];
array = array.map(function(item) {
  return +item;
});
console.log(array);


来源:https://stackoverflow.com/questions/32964649/convert-array-of-string-javascript-to-array-of-integer-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!