如何将当前变量与当前类型进行比较?

时间:2016-09-17 12:13:26

标签: javascript html

在我的代码中,我尝试使用类型字符串和数字来映射数组tmp中的当前元素。通过这种比较,我想在控制台中打印结果不同,即if是一个字符串,在同一行(整个单词)上打印,下一个单词在第二行,依此类推。但是,如果是要在新行中打印的每个数字的数字。

input number

输出数

output number

输入字符串

input string

输出字符串

Output string

HTML

<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta name="viewport" content="width=device-width">
        <meta charset="utf-8">
        <title>Exercises in JS</title>
        <script src="exercises.js"></script>
        <body>
       <label for="myText">Input array:</label>
        <input type="text" id="myText">
        <a href="#" id="sub">Submit</a>

        <br/>
        <br/>
        <label for="myText2">Input for delete:</label>
        <input type="text" id="myText2">
        <a href="#" id="sub2">Submit</a>

    </body>

    </head>
</html>

的Javascript

window.onload = function(){

inputBox =document.getElementById("myText");
btn = document.getElementById('sub');

inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');

btn.addEventListener("click",function(event){
   event.preventDefault();

   saveArr(inputBox.value);
});

btn2.addEventListener("click",function(event){
   event.preventDefault();
   removeItemAndprintNewArray(inputBox.value, inputBox2.value);
});

    function saveArr(arr) {

    var rv = [];

    for (var i = 0; i < arr.length; ++i)
       rv[i] = arr[i];

       return rv;
    }

    function removeItemAndprintNewArray(rv, number) {

    var tmp = [],
    st = "";

        for(var index in rv){
            if(rv[index] !== number){
                tmp.push(rv[index]);
            }
        }

        for (var i = 0; i < tmp.length; i++){
            if (typeof(tmp[i]) == "String"){
                st += tmp[i];
                console.log(st);
            }

            else if (typeof(tmp[i]) === "Number"){
                st += tmp[i];
                console.log(st[i]);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Javascript自动进行类型对话,如果对话失败,则返回NaN值而不是throw异常。我们用吧)

小例子

var arr = [12, "asd", 4];
arr.forEach(function(item) {
    console.log(item - 0);
});

所以你可以检查NaN,不要忘记你应该使用特殊功能isNaN()

var arr = [12, "asd", 4];
arr.forEach(function(item) {
    if(isNaN(item - 0)) {
         //do what you want with string
         console.log("string");
    };
    else {
         //do what you want with Number
         console.log("number");
    }
});