Search in a predefined set of text options

Let's say I want to see if the DOM element is a block. I can write this in three ways, depending on my mood:

// first way
if (el.currentStyle.display == "block" || el.currentStyle.display == "inline-block" || el.currentStyle.display == "table-cell")       

// second way
var blocks = {"block": 1, "inline-block": 1, "table-cell": 1};
if (el.currentStyle.display in blocks)// 

// third way
if (el.currentStyle.display.match(/block|inline-block|table-cell/))

I have a mixed feeling about all of them. At first it is too verbose if I have several options. The second one contains these arbitrary values ​​in the object (where I put 1s this time). The third one looks redundant. (What is wrong with what happens in excess?)

Do you know another, better way? If not, do I see any flaws in these three methods?

Javascript only, please.

+3
source share
5 answers

; , . , :

el.currentStyle.display.match(/(e-)?(block|cell)/)

...

, , String:

String.prototype.matches = function(what) {
    return (',' + what + ',').indexOf(',' + this + ',') > -1;
};

// Using it:
el.currentStyle.display.matches('block,inline-block,table-cell');
+2

, - , - . , - , 1, .

Overkill? . , 6 . , : -)

function isBlock(el) {
  return (el.currentStyle.display == "block" || 
          el.currentStyle.display == "inline-block" || 
          el.currentStyle.display == "table-cell");
}


// ...

if (isBlock(el)) {
  // do something
}
+2

, , undefined, ": 1". .

0

It sounds like you need the inArray function, here is one of the best search results:

Array.prototype.inArray = function (value) {
  var i;
  for (i=0; i < this.length; i++) {
    if (this[i] === value) {
      return true;
    }
  }
  return false;
};

Then the following method will look like this:

if (['block','inline-block','table-cell'].inArray(el.currentStyle.display))

Or in a more readable way:

var isBlock = ['block','inline-block','table-cell'].inArray(el.currentStyle.display);
0
source

My preferred solution for this is:

'block||inline-block||table-cell'.indexOf( el.currentStyle.display ) >= 0 

I think this will use the native code of the string and be more efficient than the array and iteration method.

0
source

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


All Articles