Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array value is undefined ... how do I test for that [duplicate]

I am trying to test to see whether a Javascript variable is undefined.

You will see that I am not expecting the value of predQuery[preId] to be 'undefined' if I don't first get an alert saying "its unbelievable". But I often do, so I am guessing that my statement

 predQuery[preId]=='undefined')  

is not matching the undefined elements properly.

if((predQuery.length < preId) || (predQuery[preId]=="") || (predQuery[preId]=='undefined')){    alert("its unbelievable");    alert(predQuery[preId]);    queryPreds[variables] = preId;    queryObjs[variables] = objId;    predQuery[preId] = variables; } else {     alert(predQuery[preId]);    var predIndex = predQuery[preId];    queryPreds[predIndex] = preId;    queryObjs[predIndex] = objId; } 

I can add more code if needed.

like image 417
Ankur Avatar asked Apr 20 '10 06:04

Ankur


People also ask

How do you check if there are duplicates in an array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do you check if an element in an array is undefined JavaScript?

Use the Array. includes() method to check if an array contains undefined values, e.g. arr. includes(undefined) . The includes method will return true if the array contains at least one undefined value and false otherwise.

How do you verify undefined values?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

How do you check if a value exists in an array JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.


1 Answers

array[index] == 'undefined' compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined', which compares the type.

like image 109
deceze Avatar answered Oct 02 '22 12:10

deceze