简体   繁体   中英

Convert array-like variable into array with integers in jQuery

I have a dynamically filled variable containing numbers formatted as text that are separated by commas.

When alerting this out for testing I get something like: var myVar = 3,5,1,0,7,5

How can I convert this variable into a valid JavaScript or jQuery array containing integers ?

I tried $.makeArray(myVar) but that doesn't work.

Simple, try this.

var myVar = 3,5,1,0,7,5;
myVarArray = myVar.split(",");

// Convert into integers 
for(var i=0, len = myVarArray.len; I < len; I++){
  myVarArray[i] = parseInt(myVarArray[i], 10);
}
// myVarArray is array of integers 

You can just do this:

var myVar = "3,5,1,0,7,5"; 
var myArr = myVar.split(',').map(function(x){return +x});

myArr will have integer array.

I changed myVar = 3,5,1,0,7,5 to myVar = "3,5,1,0,7,5" because the former wasn't valid.

I presume that it is a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM