3

检查数字是否在Javascript列表中的最快方法是什么?

我知道 indexOf >= 但对我来说似乎相当慢。

我必须每秒执行数百万次检查,而且列表很短(最多约 10 个条目)

4

3 回答 3

2

在jsperf尝试一下,但我怀疑使用对象并将数字设置为属性会比数组搜索更快。

var theList = { 1: true, 2000: true, 253: true, -12077: true, ... };

if (theList[ someNumber ]) { // see if some number is in the list

现在,就是说,您将无法在每秒数百万次的 Web 浏览器中使用 JavaScript 执行任何有用的操作,除非在极高端的机器上没有做太多其他事情。

于 2013-08-10T12:55:39.950 回答
1

那么最好使用indexof()

作为在您的情况下不受欢迎的替代方法是使用Enumerable#include

您可以使用Enumerable#include但我怀疑它是否比类似的indexof()东西更快:-

[1, 2, '3', '4', '5'].include(3);
于 2013-08-10T12:47:37.467 回答
0

如果您正在寻找理解速度,请使用array.includes

[-1, 1, 2].includes(0)  // false
[-1, 1, 2].includes(-1) // true
[-1, 1, 2].includes(-2) // false
[-1, 1, 2].includes(2)  // true
[-1, 1, 2].includes(3)  // false
于 2021-04-19T06:48:13.927 回答