我想将字符串转换为整数。我知道有内置函数可以做到这一点,但我仍然想知道为什么这个函数不起作用:
JS: -另存为js1.js
function atoi(str)
{
l = str.length;
s2 = "0"
for(i=0;i<l;i++)
{
if(str.charAt(i) != '1' || str.charAt(i) != '2' || str.charAt(i) != '3' || str.charAt(i) != '4' || str.charAt(i) != '5' || str.charAt(i) != '6' || str.charAt(i) != '7' || str.charAt(i) != '8' || str.charAt(i) != '9' || str.charAt(i) != '0')
{
break;
}
s2 = s2.concat(str.charAt(i));
}
return Number(s2);
}
HTML:
<html>
<head>
<script src="js1.js">
</script>
<Script>
function printnum()
{
n = atoi(document.getElementById('numtxt').value)
document.write(n);
}
</script>
<title>
Test JS1 functions
</title>
</head>
<body>
<input type="text" id="numtxt">
<input type="button" onclick="printnum()">
</body>
</html>
谢谢你。