确定字符串是否在JavaScript中列表中 [英] Determine if string is in list in JavaScript

查看:175
本文介绍了确定字符串是否在JavaScript中列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL中,我们可以看到字符串是否在列表中,如下所示:

In SQL we can see if a string is in a list like so:

Column IN ('a', 'b', 'c')

在JavaScript中执行此操作的好方法是什么?执行此操作非常笨重:

What's a good way to do this in JavaScript? It's so clunky to do this:

if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') {
   // do something
}

而且我不确定这个的表现或清晰度:

And I'm not sure about the performance or clarity of this:

if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
   // do something
}

或者可以使用切换功能:

Or one could use the switch function:

var str = 'a',
   flag = false;

switch (str) {
   case 'a':
   case 'b':
   case 'c':
      flag = true;
   default:
}

if (expression1 || expression2 || flag) {
   // do something
}

但这是一个可怕的混乱。有什么想法吗?

But that is a horrible mess. Any ideas?

在这种情况下,我必须使用Internet  Explorer 7作为企业内部网页面。所以 ['a','b','c']。indexOf(str)!== -1 如果没有一些语法糖就无法原生工作。

In this case, I have to use Internet Explorer 7 as it's for a corporate intranet page. So ['a', 'b', 'c'].indexOf(str) !== -1 won't work natively without some syntax sugar.

推荐答案

EcmaScript 6



如果您使用的是ES6,则可以构建一个项目数组,并使用 包含

['a', 'b', 'c'].includes('b')

这比有一些固有的好处indexOf 因为它可以正确测试列表中是否存在 NaN ,并且可以匹配缺少的数组元素,例如<$ c中的中间数组元素$ c> [1,,2] 到未定义 includes 也适用于 JavaScript类型数组,例如 Uint8Array

This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined. includes also works on JavaScript typed arrays such as Uint8Array.

您可以在字符串中添加新的 isInList 属性,如下所示:

You could add a new isInList property to strings as follows:

if (!String.prototype.isInList) {
   String.prototype.isInList = function() {
      let value = this.valueOf();
      for (let i = 0, l = arguments.length; i < l; i += 1) {
         if (arguments[i] === value) return true;
      }
      return false;
   }
}

然后像这样使用它:

'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false

你可以为<$ c做同样的事情$ c> Number.prototype 。

如果你是使用现代浏览器, indexOf 始终有效。但是,对于IE8及更早版本,您需要一个polyfill。

If you are using a modern browser, indexOf always works. However, for IE8 and earlier you'll need a polyfill.

如果 indexOf 返回-1,则该项为不在列表中。请注意,此方法无法正确检查 NaN ,虽然它可以匹配显式的 undefined ,但无法将缺少的元素与 undefined 匹配,如数组 [1,,2]

If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can’t match a missing element to undefined as in the array [1, , 2].

你总是可以使用符合标准的自定义polyfill ,使其在旧版浏览器中运行。

You can always use a standards-compliant custom polyfill to make this work in older browsers.

在这种我必须为Internet Explorer 7制作解决方案的情况下,我推出了我自己的更简单版本的 indexOf()函数,该函数不符合标准:

In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf() function that is not standards-compliant:

if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(item) {
      var i = this.length;
      while (i--) {
         if (this[i] === item) return i;
      }
      return -1;
   }
}

但是,我不认为修改<$ c从长远来看,$ c> Array.prototype 是最好的答案。在JavaScript中修改对象数组原型可能会导致严重的错误。您需要决定在您自己的环境中这样做是否安全。首要注意的是,在中使用迭代一个数组(当Array.prototype添加了属性时)将返回新的函数名作为其中一个键:

However, I don't think modifying Array.prototype is the best answer in the long term. Modifying Object and Array prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys:

Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!

您的代码现在可以正常运行,但是将来会有人添加第三方JavaScript库或插件不热心防范继承密钥,一切都可以破解。

Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.

在枚举过程中避免破坏的旧方法是检查每个值,看是否对象实际上将它作为非继承属性与 if(arr.hasOwnProperty(x))只有使用 x

The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x.

新的ES6避免这个额外关键问题的方法是使用 而不是中的代表(让x of arr)。但是,除非您能保证所有代码和第三方库严格遵守此方法,否则出于此问题的目的,您可能只想使用 includes 如上所述。

The new ES6 way to avoid this extra-key problem is to use of instead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes as stated above.

这篇关于确定字符串是否在JavaScript中列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆