我如何分离数字和字符串(初学者,JS)

  1. 我想知道为什么其他代码不起作用我尝试转换为数字但
    仍然不起作用。

** 图片 1 图片 2

   function KareAlan() {

 var kare1 = document.getElementById("kare1")

  .value;

 var kare1n = parseInt(kare1, 10)


 if (typeof kare1n == "number") {

  kare1 = kare1 * kare1 * kare1;

  document.getElementById("sonuc").innerHTML =

   "Result:" + " " + kare1;

 } else if (typeof kare1n == "string") {


  document.getElementById("sonuc").innerHTML =

   "This procces is not possible,you should input at least one number";

 }


}


慕婉清6462132
浏览 137回答 3
3回答

慕妹3242003

我建议您阅读更多有关html 表单的内容:function KareAlan() { var kare1 = document.getElementById("kare1").value; var kare1n = parseInt(kare1, 10) document.getElementById("sonuc").innerHTML =   "Result:" + " " + kare1}<label for="kare1">Input Number</label><br><input type="number" value="5" id="kare1" oninput="KareAlan()"></input><h3 id="sonuc"></h3>

紫衣仙女

使用 !isNaN(number) 检查数字。我们使用 isNaN(),如果不是数字则返回 true,然后我们否定该语句以获得一个如果它是数字则返回 true 的函数。

小唯快跑啊

正如其他人指出的那样,该值NaN是 a number。您需要在运行代码typeof之前进行检查,看看会发生什么parsevar theApple&nbsp; = "Apple";var theNumber = 1234;console.log(&nbsp; "log line 1: " + theApple,&nbsp; parseInt(theApple, 10),&nbsp; "| typeof: " + typeof(theApple),&nbsp; "| typeof parsedInt: " + typeof(parseInt(theApple, 10)),);console.log(&nbsp; "log line 2: " + theNumber,&nbsp; parseInt(theNumber, 10),&nbsp; "| typeof: " + typeof(theNumber),&nbsp; "| typeof parsedInt: " + typeof(parseInt(theNumber, 10)),);// or simplyconsole.log("log line 3: ", !isNaN(theApple));console.log("log line 4: ", !isNaN(theNumber));// the problem with isNan is a value like this is also a NaN:console.log("log line 5: ", !isNaN('0.0314E+2'));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript