Javascript String to int conversion [英] Javascript String to int conversion
问题描述
我在页面中嵌入了以下JS:
I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id
将类似于adult0,我需要把那个字符串分成成人和0 - 这部分工作正常。
id
will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
当我尝试增加0时出现问题。你可以看到我使用Math.round将其转换为整数,然后加1 - 我希望在此之后0为1。但是,它似乎没有将它转换为整数,因为我得到 01
,而不是 1
。当用adult1测试时,我得到的警告是 11
。
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01
, not 1
. When testing this with adult1 the alert I get is 11
.
我正在使用这个问题供参考,并且还试过 var number + = id.substring(indexPos);
,打破了JS(意外标识符'+ ='
)
I'm using this question for reference, and have also tried var number += id.substring(indexPos);
, which breaks the JS (unexpected identifier '+='
)
有谁知道我在做什么错误?有没有更好的方法呢?
Does anyone know what I'm doing wrong? Is there a better way of doing this?
推荐答案
parseInt()
function解析字符串
并返回整数
,10是基数或基数
[DOC]
The parseInt()
function parses a string
and returns an integer
,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
这篇关于Javascript String to int conversion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!