【问题标题】:javascript: Check if element exist in pre determined set of values [duplicate]javascript:检查元素是否存在于预先确定的一组值中[重复]
【发布时间】:2017-09-17 05:27:12
【问题描述】:

我们有 id 列表,即 1、2、3。

有一个函数接受 id 并返回如果传递的 id 是否在此列表中:

function isIdInList(id) {
    return [1,2,3].includes(id); 
}

function isIdInList(id) {
    return [1,2,3].indexOf(id) > -1;
}

即isIdInList(1) 返回真。 isIdInList(5) 返回 false。

什么是最好的解决方案,以上两个之一或任何其他? (考虑到列表是硬编码的,并且该解决方案应该与所有浏览器兼容。)

【问题讨论】:

  • includes 不受 ie 或 edge 支持,这就是我选择indexOf 的原因。
  • 这取决于检查的频率以及数组的大小。
  • 它的数组很小,即20个元素,但经常被检查
  • Edge 支持includes 就好了。

标签: javascript


【解决方案1】:

Array.prototype.includes 来自 ES2016 规范。并非所有网络浏览器都很好地支持它(特别是如果它们不是最新的......),因此您可能应该使用带有indexOf 的解决方案以获得完全兼容性。

当然,如果你用 Babel 或 Traceur 编译你的代码,你可以使用 includes,但是添加一个像 MDN documentation 中建议的 polyfill 是明智的:

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1. 
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

【讨论】:

  • (1) 在IE以外的浏览器中得到很好的支持。 (2) 仅仅转译对你没有帮助,除非你包含一个 polyfill,你可以在没有转译的情况下做到这一点。
  • @torazaburo 嘿!感谢这个有趣的评论。 :) (1) 这假设您的网络浏览器是最新的,但对于网络上的每个人来说,情况并非如此。 (2) 转译仍然是 ES6 项目工作流程的一部分,但你是对的,我将稍微修改一下我的答案。
  • 我非常熟悉许多主要软件公司的浏览器支持政策,其中绝大多数只支持Chrome和FF等最新的3-5个版本的浏览器。原因很简单,他们不需要支持比这更远的任何东西。只要您的计算机处于开启状态,这些浏览器通常会自行更新。实际上,您必须竭尽全力停止自动更新。
猜你喜欢
  • 1970-01-01
  • 2015-08-03
  • 2011-11-14
  • 2012-12-31
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多