How to check undefined values ​​in IE8?

I have this in my javascript:

console.log(filters); console.log('----'); console.log(filters.max_price); 

In Chrome, this shows. This behavior is expected .

 Object {max_price: undefined, sort_by: undefined, distance: undefined, start: undefined, num: undefined} ---- undefined 

In IE8, the log shows this:

 LOG: Object Object ---- LOG: String 

Why does IE8 think this is a string? I need to know if it is undefined.

I have a lot of code that sets default values.

 if(typeof filters.max_price == undefined){ //I use this technique a lot! filter.max_price = 2000; } 

How can I check undefine-ds in IE8? Should I do this? It seems to work (yay ...), but it seems cheap and hacked.

 if(!filters.max_price || typeof filters.max_price == 'undefined'){ 

Is there an easy way to do this with underscore ?

+6
source share
2 answers

You can use this approach, but it will not lead to a significant reduction in your code:

 filters.max_price = filters.max_price || 2000; 

This, however, will overwrite the value if it is 0. The best approach remains:

 if(typeof filters.max_price === 'undefined'){ // init default } 
+5
source

You can use the operand to set the default value:

 filters.max_price = filters.max_price || 2000; 

To check if the value is a number (which I assumed the price), you can use

 if(isNaN(filters.max_price)) { //enter code here } 

It also filters out undefined as not a number.

0
source

Source: https://habr.com/ru/post/943684/


All Articles