javascript的问题 [英] A problem with javascript

查看:67
本文介绍了javascript的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我得到了一个非响应式JavaScript代码。代码工作正常,直到它到达第4行,而不是其他任何事情发生。没有显示提醒信息。

这里是代码:





Hi guys,
I got a non responsive code of JavaScript type. The code works fine until it reaches line 4, than nothing else happen. There is no alert message showing.
here's the code:


var ageAsString = prompt("what is your age? ", "");
var age = number(ageAsString);
alert(age);
if (age < 40) {
    alert("You are so young...");
} else {
    alert("Ok");
}

alert("thank you");





代码是用VS 2017编写的。

谢谢,

Avri < br $> b $ b

我尝试了什么:



我试过试试它在几个浏览器上,我得到了相同的结果。



如果我在标签内运行代码,一切都运行得很好。

问题当我通过插入一个链接调用此代码时上升



the code is written in VS 2017.
Thanks,
Avri

What I have tried:

I've tried to run it on several browser and I got the same results.

If I run the code from within the tag, everything works beautifully.
The problem rises when I call this code by inserting a link to it

推荐答案

区分大小写是问题:)



Case sensitivity is the problem :)

var age = number(ageAsString);





应该是:





Should be:

var age = Number(ageAsString);


不知道你在哪里得到函数number从?



试试parseInt



not sure where you got the function "number" from?

try parseInt

var ageAsString = prompt("what is your age? ", "");
var age = parseInt(ageAsString);
alert(age);
if (age < 40) {
    alert("You are so young...");
} else {
    alert("Ok");
}

alert("thank you");





您应该调查javascript:

JavaScript调试 [ ^ ]






实际上没有必要创建一个ex tra变量只是用它作为给定值的类型修饰符。



然而你需要来验证用户输入的东西这是数字类型而不是任何其他类型的字符串。



.
Actually there is no need to create an extra variable just and only to use it as a type modifier of the given value.

However you DO need to validate that user inputs something that is number type and not any other kind of string.

var ageAsString = prompt("what is your age? ", "");
var age = Number(ageAsString);

// you convert input string to Integer immediately, no need to create extra variable
var age = parseInt(prompt("what is your age?", "")); 


// you first check that age is indeed a number and not a Not A Number (NaN)

if (isNaN(age)) { // if age is NaN then alert the user to stop messing around

    alert("You have to insert a number mate")

// in any other case , the script continues to do your stuff
} else { 

    alert(age);

    if (age < 40) {
        alert("You are so young...");
    } else {
        alert("Ok");
    }

}

alert("thank you") // you are welcome



现在有一个问题,如果你说让我们说 23a 它将作为一个数字而不是NaN传递。



对于这些情况,你必须制作更复杂的验证器但是现在我墨水你已经知道如何使你的脚本更加稳固。




Now there is a catch, if you put let's say 23a it will pass as a number and not a NaN.

For these cases you'll have to make more sophisticated validators but for now I think you have already got the idea of how to make your script more solid.

.


这篇关于javascript的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆