最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

simplify javascript if statement where conditions are identical except for variable - Stack Overflow

programmeradmin7浏览0评论

I apologize if this is a duplicate question. It's such a use-case question that it seems everyone has their own version.

I'm wondering if this can be simplified:

if ($('.taxclass').text().indexOf(tax1)>-1 || $('.taxclass').text().indexOf(tax2)>-1) {}

I apologize if this is a duplicate question. It's such a use-case question that it seems everyone has their own version.

I'm wondering if this can be simplified:

if ($('.taxclass').text().indexOf(tax1)>-1 || $('.taxclass').text().indexOf(tax2)>-1) {}
Share asked Feb 26, 2013 at 16:30 Adam CookAdam Cook 6202 gold badges7 silver badges21 bronze badges 4
  • 1 absolutly, use pure js instead of jquery, thats a 40-70kb reduce :) – Toping Commented Feb 26, 2013 at 16:33
  • 1 @Ark doesn't really matter if OP has other jQuery dependencies, which is most likely the case if he is posting jQuery code. – Fabrício Matté Commented Feb 26, 2013 at 16:34
  • I can't get over how quickly the answers e on this site. :) – Adam Cook Commented Feb 26, 2013 at 16:37
  • @FabrícioMatté you're doing a assumption of my assumption, that's a inception :) – Toping Commented Feb 26, 2013 at 16:39
Add a ment  | 

6 Answers 6

Reset to default 4

It's pretty simple as it stands, but you could make it a bit less redundant mainly by getting the elements text only once and reusing the variable:

var text = $('.taxclass').text();
if (text.indexOf(tax1)>-1 || text.indexOf(tax2)>-1) {

}

A further note could be to reduce the traversal of the DOM by using an identifier and looking only for a distinct element (if that suits your needs) instead of every possible thing that has the class taxclass.

var txt = $('.taxclass').text();
if (txt.indexOf(tax1)>-1 || txt.indexOf(tax2)>-1) {}

One super quick way would be not to duplicate $('.taxclass').text()

Try something like

var tax = $('.taxclass').text();
if (tax.indexOf(tax1)>-1 || tax.indexOf(tax2)>-1) {}

You can store $('.taxclass').text() in a variable, or use regex.

var str = $('.taxclass').text();

if (str.indexOf(tax1) > -1 || str.indexOf(tax2) > -1)

// Or with regex
if(/(text1)|(text2)/.test($('.taxclass').text())
{}

Quick and dirty:

text.indexOf(tax1+"~"+tax2)>-1

Functional, works on n strings, but verbose:

[tax1, tax2].some(function(s) { return s.indexOf(text)>-1 })

As a prototype:

String.prototype.foundIn = function() {
    var s=this; return Array.prototype.slice.call(arguments).some(function(m)
       {return m.indexOf(s)>-1});
};

Usage:

$('.taxclass').text().foundIn(tax1, tax2)

What about:

f = function (x) { return $('.taxclass').text().indexOf(x) > -1; }
if (f(tax1) || f(tax2)) {}
发布评论

评论列表(0)

  1. 暂无评论