Reputation: 2218
I have the following simple Javascript code.
var input = [
'one',
'two'
];
for(var i in input){
if(typeof input[i+1] == undefined){
console.log("i is the last index");
}
}
I don't know if I did something wrong but the console.log()
part never executes. Which means it never enters the if
condition while clearly the index beyond the last index is undefined.
You can see it in this fiddle.
Please explain..
Upvotes: 0
Views: 108
Reputation: 27529
typeof
returns a string. You're comparing it to the undefined
value.
Use
if(typeof input[i+1] === "undefined"){
Upvotes: 0
Reputation: 1734
This:
if(typeof input[i+1] == undefined){
Should be:
if(input[i+1] === undefined){
(no need to use typeof
)
Upvotes: 5
Reputation: 66389
Turns out that the type of i
is string, so to make the code work properly you need to cast it to integer:
for(var i in input){
if(typeof input[parseInt(i, 10) + 1] === "undefined") {
console.log(i + " is the last index");
}
}
Upvotes: 0
Reputation: 3280
That is because the typeof operator returns an string. You need to compare with a string "undefined" like so:
var input = [
'one',
'two'
];
for(var i in input){
if(typeof input[i+1] == "undefined"){
console.log("i is last");
}
}
Upvotes: 1
Reputation: 3026
javascript typeof
operator always returns string, so you should compare against 'undefined'
like this:
if(typeof input[i+1] === 'undefined')
Here is an updated fiddle - http://jsfiddle.net/Pharaon/V7EJZ/
Upvotes: 0
Reputation: 5841
Undefined should be a string, "undefined"
, working fiddle: http://jsfiddle.net/asifrc/vRTsE/1/
Upvotes: 3