Santiya
Santiya

Reputation: 195

How to compare the current variable with current type?

In my code I try to comapare the current element from the array tmp with the types string and number. With this compare I want to print in the console the result different, i.e. if is a string to print it on the same line(the whole word), the next word to be on the second line and so on. But if is a number every digit to print in the new line.

input number

Output number

output number

Input string

input string

Output 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]);
            }
        }
    }
}

Upvotes: 0

Views: 49

Answers (1)

Nikita
Nikita

Reputation: 1082

Javascript automatically makes type conversations, and if conversation fails it returns NaN value instead of throw exception. Let's use it)

Small example

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

So you can check on NaN, don't forget that you should use special function 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");
    }
});

Upvotes: 1

Related Questions