我如何使用if,else if和else语句来验证两个字符串

时间:2019-02-02 01:29:07

标签: javascript string if-statement

我是JavaScript的新手,并且我热衷于学习。我想做的是使用if,else语句。我正在尝试验证两种类型的字符串。我似乎无法核实这些数字,也无法终生知道。任何提示,将不胜感激。

    

JavaScript:示例类型

<script>
    var string1 = 'w3';
    var string2 = (1); 

    if (typeof string1 == 'w3') {
        document.write(string1 + " is a number <br/>");
        else if (typeof string2 == (1) {
            document.write(string2 + "is a number <br/>");
        }
    } else {
        document.write(string2 + " is not a number <br/>");
    }

</script>

2 个答案:

答案 0 :(得分:0)

Javascript只有6种本机类型:“数字”,“字符串”,“布尔”,“对象”,“函数”和“未定义”。 typeof运算符试图找出变量的类型。因此:

console.log(typeof 'w3');    // will print 'string'
console.log(typeof 1);    //will print 'number'
console.log(typeof true);    //will print 'boolean'
console.log(typeof {});    //will print 'object'
console.log(typeof function(){});    //will print 'function'
console.log(typeof undefined);    //will print 'undefined'

var v1 = 'str';
if (typeof v1 == 'string') {
    console.log('string');
} else {
    console.log('not a string');
}

// and so forth.

尝试在Chrome的开发工具中玩这些东西(即,按F12键并在控制台中键入命令)。如果您不熟悉,如果您使用Javascript进行编码,那么开发工具将改变您的生活。

答案 1 :(得分:0)

当前,您正在使用typeof运算符将变量与其值进行比较。 Javascript有六种类型:数字,字符串,布尔值,对象,函数和未定义。

案例1

如果要查看变量是否为特定类型,请使用typeof,如下所示:

<script>
    var string1 = 'w3';
    var string2 = 1; 

    if (typeof string1 === 'string') {
        document.write(string1 + " is a number <br/>");
        else if (typeof string2 === 'number') {
            document.write(string2 + "is a number <br/>");
        }
    }
    else {
        document.write(string2 + " is not a number <br/>");
    }

</script>

案例2

如果要查看变量是否等于值,只需使用严格的比较运算符(===):

<script>
    var string1 = 'w3';
    var string2 = 1; 

    if (string1 === 'w3') {
        document.write(string1 + " is a number <br/>");
        else if (string2 === 1) {
            document.write(string2 + "is a number <br/>");
        }
    }
    else {
        document.write(string2 + " is not a number <br/>");
    }

</script>

首先,始终最好使用严格的等于运算符(===)而不是等于运算符(==)。您可以阅读有关此here的更多信息。其次,请使用正确的缩进和语法使代码更易读。如果您希望人们能够更轻松地阅读您的代码,那么这非常重要。谢谢您阅读我的回答,祝您好运!