Sky*_*ger 25 javascript string int type-conversion
我在页面中嵌入了以下JS:
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);
Run Code Online (Sandbox Code Playgroud)
id 将是像adult0一样的东西,我需要把它串起来分成成人和0 - 这部分工作正常.
当我尝试增加0时出现问题.正如您所看到的,我使用Math.round将其转换为整数,然后将其加1 - 我希望在此之后0为1.但是,它似乎并没有将它转换为整数,因为我得到的01不是1.当用adult1测试时,我得到的警报是11.
我正在使用这个问题作为参考,并且也尝试过var number += id.substring(indexPos);,这打破了JS(unexpected identifier '+=')
有谁知道我做错了什么?有没有更好的方法呢?
Cha*_*JRA 36
该parseInt()函数解析a string并返回一个integer,10是Radix或Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
Run Code Online (Sandbox Code Playgroud)
这与JavaScript的+运算符有关 - 如果数字和字符串被"添加",则数字将转换为字符串:
0 + 1; //1
'0' + 1; // '01'
Run Code Online (Sandbox Code Playgroud)
要解决此问题,请使用+一元运算符,或使用parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
Run Code Online (Sandbox Code Playgroud)
一元运算+符将其转换为数字(但如果它是小数,则会保留小数位),并且parseInt()不言自明(转换为数字,忽略小数位).
第二个参数是parseInt()在放置前导0时使用正确的基数所必需的:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
Run Code Online (Sandbox Code Playgroud)
还有parseFloat(),如果你需要在小数字符串转换为自己的数值- +可以做到这一点,但它的行为稍有不同:这是另一回事,虽然.
JS会认为0实际上是一个字符串,可以使用parseInt()函数将其转换为int,例如:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
Run Code Online (Sandbox Code Playgroud)
如果无法将数字转换为int,它将返回NaN,因此我建议在生产中使用的代码中也进行检查,或者至少在不确定100%输入的情况下也是如此。
虽然parseInt这是执行此操作的官方函数,但您可以使用以下代码实现相同的目的:
number*1
Run Code Online (Sandbox Code Playgroud)
优点是您可以节省一些字符,如果您的代码需要进行大量此类对话,这可能会节省带宽。
转换方式Number Class:-
例如:
var n = Number("103");
console.log(n+1)
Run Code Online (Sandbox Code Playgroud)
输出: 104
注意:- Number是类。当我们传递字符串时,构造函数Number class将转换它。
| 归档时间: |
|
| 查看次数: |
86555 次 |
| 最近记录: |