Home > OS >  In javascript, How to check if the last element of an array is a number or not. Note that the last e
In javascript, How to check if the last element of an array is a number or not. Note that the last e

Time:10-18

console.log("case 1")
var event = "Year 2021";
console.log(typeof(parseInt(event.split(" ").pop())) === "number");
console.log("case 2")
var event = "Year mukesh";
console.log(typeof(parseInt(event.split(" ").pop())) === "number");
console.log("case 3")
var event = "Year mukesh";
console.log(typeof(event.split(" ").pop()) === "number");
console.log("case 4")
var event = "Year 2021";
console.log(typeof(event.split(" ").pop()) === "number");
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

case 1 when we have a proper number in last place with using parseInt gives true and that is legit!

case 2 when we have a string in last place and still using parseInt...should give false but because of parseInt it gives us valid number type

case 3 when we have a string in last place without using parseInt... gives false that too is legit!

case 4 when we have a number in last place without using parseInt.. gives false that is too is legit! well because "2021" is a string because 2021 is indeed enclosed within " ".

Now how do I check if the last element of the array is a string or an integer because from the user I could receive any combination either a "Hello darkness" or "Hello 221".

Check on jsfiddle for more clarification

CodePudding user response:

Use isNaN to determine whether a value is NaN or not:

console.log("case 1")
var event = "Year 2021";
console.log('Is a number?', !isNaN(event.split(" ").pop()));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related