admin管理员组

文章数量:1289623

I am wondering to how to get number from an array. I have tried its give me NaN error

<script type="text/javascript">

$(function(){

var Arr = [ 'h78em', 'w145px', 'w13px' ]

alert(parseInt(Arr[0]))


})
</script>

I am wondering to how to get number from an array. I have tried its give me NaN error

<script type="text/javascript">

$(function(){

var Arr = [ 'h78em', 'w145px', 'w13px' ]

alert(parseInt(Arr[0]))


})
</script>
Share Improve this question asked Aug 30, 2012 at 8:03 JitenderJitender 7,96932 gold badges116 silver badges218 bronze badges 2
  • 2 That's because h78em is not a number. – verdesmarald Commented Aug 30, 2012 at 8:04
  • 2 If you just want all the digits in the string you could use a regex: parseInt(Arr[0].replace(/\D/g), ''). Do you care about more plex cases like abc123def456? – verdesmarald Commented Aug 30, 2012 at 8:10
Add a ment  | 

7 Answers 7

Reset to default 3

try with

+Arr[0].replace(/\D/g, '');

Example fiddle: http://jsfiddle/t6yCV/

Starting + is working like parseInt() and it is necessary if you need to perform some mathematical operation with the number obtained: in fact

typeof Arr[0].replace(/\D/g,'')  // String
typeof +Arr[0].replace(/\D/g,'') // Number

Try:

['h78em', 'w145px', 'w13px']
 .map(function(a){return ~~(a.replace(/\D/g,''));});
 //=> [78, 145, 13]

See also

Or use a somewhat more elaborate String prototype extension:

String.prototype.intsFromString = function(bine){
 var nums = this.match(/\d{1,}/g);
 return !nums ? 0 
         : nums.length>1 ? bine ? ~~nums.join('') 
           : nums.map(function(a){return ~~a;}) 
         : ~~nums[0];
};
// usage
'abc23'.intsFromString();          //=> 23
'3abc121cde'.intsFromString();     //=> [3,121]
'3abc121cde'.intsFromString(true); //=> 3121
'abcde'.intsFromString();          //=> 0
// and ofcourse
['h78em', 'w145px', 'w13px'].map(function(a){return a.intsFromString();});
//=> [78, 145, 13]

You can build a function that builds the number from your string:

function stringToNum(str){
  num = 0;
  for (i = 0; i < str.length; i++) 
    if (str[i] >= '0' && str[i] <= '9') 
      num = num * 10 + parseInt(str[i]);
  return num;
}

jsFiddle : http://jsfiddle/8WwHh/

Try this:

var Arr = [ 'h78em', 'w145px', 'w13px' ]

function stringToNum(str){
  return str.match(/\d+/g);

}

alert(stringToNum(Arr[0]));

http://jsfiddle/8WwHh/1/

Yet another quick and dirty solution:

alert(Arr[0].match("\\d+"));

How about

alert(parseInt(Arr[0].replace(/[a-z_A-Z]/g,"")));

jsfiddle

Try it,this regex is better

parseInt('h343px'.replace(/^[a-zA-Z]+/,''),10)

本文标签: javascriptParseInt() method on arrayStack Overflow