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 likeabc123def456
? – verdesmarald Commented Aug 30, 2012 at 8:10
7 Answers
Reset to default 3try 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
版权声明:本文标题:javascript - ParseInt() method on array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741438077a2378754.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论