最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parsing every element of an array as an integer - Stack Overflow

programmeradmin5浏览0评论

I have a string which I need to split into an array and then perform mathematical functions on each element of the array.

Currently I am doing something like this. (Actually, I am doing nothing like this, but this is a very simple example to explain my question!

var stringBits = theString.split('/');

var result = parseInt(stringBits[0]) + parseInt(stringBits[3]) / parseInt(stringBits[1]);

What I would like to know is if there is a way I can convert every element of an array into a certain type that would stop me from having to explicitly parse it each time.

I have a string which I need to split into an array and then perform mathematical functions on each element of the array.

Currently I am doing something like this. (Actually, I am doing nothing like this, but this is a very simple example to explain my question!

var stringBits = theString.split('/');

var result = parseInt(stringBits[0]) + parseInt(stringBits[3]) / parseInt(stringBits[1]);

What I would like to know is if there is a way I can convert every element of an array into a certain type that would stop me from having to explicitly parse it each time.

Share Improve this question asked Nov 20, 2009 at 10:39 TobyToby 8,79213 gold badges48 silver badges70 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 11

An easier method is to map to the Number object

result= stringBits.map(Number); 

javascript 1.6. has map() ( https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map ), so you can do something like

intArray = someArray.map(function(e) { return parseInt(e) })

You can just loop through it:

for(var i = 0; i < stringBits.length; i++) {

    stringBits[i] = parseInt(stringBits[i]);
}
["1","2"].map(Number)
result: [1,2]

If you add a plus (+) sign in front of your strings they should be converted to numeric.

For example, this will print 3:

var x = "1";
var y = "2";
alert((+x) + (+y));

But I am not sure if this is portable to all browsers.

Your code will become:

var stringBits = theString.split('/');
var result = (+stringBits[0]) + (+stringBits[3]) / (+stringBits[1]);

But this is just a hack, so use with care.

I think the parseInt states better what you are trying to do, but you should delegate this responsibility to another method that returns the final data that you need to process. Convert and then process, don’t convert while processing. Your code will be easier to read.

发布评论

评论列表(0)

  1. 暂无评论