如何在JavaScript中修复Number.isInteger()函数

时间:2017-02-28 11:04:16

标签: javascript jquery html integer

当我按下按钮时,它会从textarea中检索一个值 HTML代码

<textarea rows="10" cols="17" id="list_card" placeholder="Insert Card Numbers"></textarea>
<input  name="infoDominio" type="submit"  class="btn btn-primary btn-block btn-sm" value="Add Card" onclick="add_card()">

Javascript代码

var res = myVar[0];
var ress = 4567891;
var val1 = Number.isInteger(res);
var val2 = Number.isInteger(ress);
document.write(myVar[0]+" "+val1+" "+val2+" "+res);

myVar[0] = 4567891; myVar[0]值来自textarea。但我无法获得正确的输出。我认为val1应该是真的。输出看起来像这样。你能告诉我怎样才能得到val1 = true。

4567891 false true 4567891

4 个答案:

答案 0 :(得分:1)

textarea将生成string而不是integer

您需要parseinteger

var res = parseInt(myVar[0]);

作为旁注:用户可以在textarea中键入非整数值。也许您正在寻找input type="number"/>

答案 1 :(得分:1)

我觉得这对你很有用

&#13;
&#13;
function add_card(){
myVar =  document.getElementById("list_card").value;
var res = Number(myVar);
var ress = 4567891;
var val1 = Number.isInteger(res);
var val2 = Number.isInteger(ress);
document.write(myVar+" "+val1+" "+val2+" "+res);
}
&#13;
<textarea rows="10" cols="17" id="list_card" placeholder="Insert Card Numbers"></textarea>
<input  name="infoDominio" type="submit"  class="btn btn-primary btn-block btn-sm" value="Add Card" onclick="add_card()">
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需将val1赋值更改为此

即可
var val1 = Number.isInteger(parseInt(res));

答案 3 :(得分:0)

使用此正则表达式

  • / ^ - &gt;字符串的开头
  • \ d + - &gt;一次或多次出现数字(\ d)
  • $ / - &gt;字符串结尾

function add_card(){
var res = document.getElementById('list_card').value;
var ress = 4567891;
var val1 = /^\d+$/.test(res);
var val2 = /^\d+$/.test(ress);
document.write(res+" "+val1+" "+val2+" "+ress);
}
<textarea rows="10" cols="17" id="list_card" placeholder="Insert Card Numbers"></textarea>
<input  name="infoDominio" type="submit"  class="btn btn-primary btn-block btn-sm" value="Add Card" onclick="add_card()">