如何在JavaScript中将字符串转换为整数?
当前回答
将数字的乘法与各自的十次幂相加:
即:123=100+20+3=1100+2+10+31=1*(10^2)+2*(10^1)+3*(10^0)
function atoi(array) {
// Use exp as (length - i), other option would be
// to reverse the array.
// Multiply a[i] * 10^(exp) and sum
let sum = 0;
for (let i = 0; i < array.length; i++) {
let exp = array.length - (i+1);
let value = array[i] * Math.pow(10, exp);
sum += value;
}
return sum;
}
其他回答
以下是最简单的解决方案
let myNumber = "123" | 0;
更简单的解决方案
let myNumber = +"123";
我喜欢这个把戏:
~~"2.123"; //2
~~"5"; //5
双位负数在小数点之后会丢弃任何内容,并将其转换为数字格式。我被告知它比调用函数等稍快,但我并不完全相信。
我刚才在这里看到的另一个方法(一个关于JavaScript>>>运算符的问题,它是一个零填充右移),它显示了用这个运算符将数字移位0将数字转换为uint32,如果您也希望它无符号,这是很好的。同样,这将转换为无符号整数,如果使用有符号数字,这可能会导致奇怪的行为。
"-2.123" >>> 0; // 4294967294
"2.123" >>> 0; // 2
"-5" >>> 0; // 4294967291
"5" >>> 0; // 5
在我看来,没有答案涵盖所有边缘情况,因为解析浮点值会导致错误。
function parseInteger(value) {
if(value === '') return NaN;
const number = Number(value);
return Number.isInteger(number) ? number : NaN;
}
parseInteger("4") // 4
parseInteger("5aaa") // NaN
parseInteger("4.33333") // NaN
parseInteger("aaa"); // NaN
函数doSth(){var a=document.getElementById('input').value;document.getElementById('number').innerHTML=toNumber(a)+1;}函数toNumber(str){return+str;}<input id=“input”type=“text”><input onclick=“doSth()”type=“submit”><span id=“number”></span>
确保获得有效整数的最安全方法:
let integer = (parseInt(value, 10) || 0);
示例:
// Example 1 - Invalid value:
let value = null;
let integer = (parseInt(value, 10) || 0);
// => integer = 0
// Example 2 - Valid value:
let value = "1230.42";
let integer = (parseInt(value, 10) || 0);
// => integer = 1230
// Example 3 - Invalid value:
let value = () => { return 412 };
let integer = (parseInt(value, 10) || 0);
// => integer = 0
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- JavaScript: override alert()
- 重置setTimeout