javascript 数组上的 ParseInt() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12192450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:32:56  来源:igfitidea点击:

ParseInt() method on array

javascriptjquery

提问by Carlos

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

我想知道如何从数组中获取数字。我试过它给我 NaN 错误

<script type="text/javascript">

$(function(){

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

alert(parseInt(Arr[0]))


})
</script>

回答by Fabrizio Calderan

try with

尝试

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

Example fiddle: http://jsfiddle.net/t6yCV/

小提琴示例:http: //jsfiddle.net/t6yCV/

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

开始+工作就像这样parseInt(),如果您需要对获得的数字执行一些数学运算,这是必要的:事实上

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

回答by KooiInc

Try:

尝试:

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

See also

也可以看看

Or use a somewhat more elaborate Stringprototype extension:

或者使用更复杂的String原型扩展:

String.prototype.intsFromString = function(combine){
 var nums = this.match(/\d{1,}/g);
 return !nums ? 0 
         : nums.length>1 ? combine ? ~~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]

回答by Dhanasekar

Try this:

试试这个:

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

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

}

alert(stringToNum(Arr[0]));

http://jsfiddle.net/8WwHh/1/

http://jsfiddle.net/8WwHh/1/

回答by gabitzish

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.net/8WwHh/

jsFiddle:http: //jsfiddle.net/8WwHh/

回答by Snake Eyes

How about

怎么样

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

jsfiddle

提琴手

回答by MAK

Yet another quick and dirty solution:

另一个快速而肮脏的解决方案:

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

回答by yao lu

Try it,this regex is better

试试看,这个正则表达式更好

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