在 Javascript 数组中查找元素的有效方法

发布于 2024-07-15 04:32:48 字数 639 浏览 4 评论 0原文

我正在使用带有标题的数组。 每个标题索引对应于数据库中的一个 id,该数据库包含该给定标题的 html。

假设我有一个包含其中一个标题的字符串。

title = "why-birds-fly";
titles[] // an array which contains all the titles

要使用字符串“title”来获取相应的 id,我可以这样做:

for (i = 0; i < titles.length-1; i++) {
  if (titles[i] == title)
    return i+1;
}

我可以使用的另一种方法是创建一个关联数组以及与标题完全相反的标题数组。 也就是说,它使用字符串作为索引并返回数字。

titles_id {blah:0,why-birds-fly:1,blah2:2}

然后我可以通过以下方式访问 ID:

return titles_id[title]+1;

考虑 CPU、内存等,什么最有效?

另外,如果我的逻辑有问题,请告诉我。

谢谢 威廉

I am using an array with titles. Each titles index corresponds to an id in a database which contains html for that given title.

Lets say I have a string which contains one of the titles.

title = "why-birds-fly";
titles[] // an array which contains all the titles

To use the string "title" to get the corresponding id I could do:

for (i = 0; i < titles.length-1; i++) {
  if (titles[i] == title)
    return i+1;
}

Another method I could use is to create an associative array together with the titles array which is the exact opposite of titles. That is, it uses the string as an index and returns the number.

titles_id {blah:0,why-birds-fly:1,blah2:2}

I could then access the ID by:

return titles_id[title]+1;

What would be most effective considering CPU, Memory, etc?

Also, please let me know if my logic is all wrong.

Thanks
Willem

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

疧_╮線 2024-07-22 04:32:48

线性搜索方法的复杂度为 O(n),我认为最坏的情况是关联数组方法可能是 O(log n),(如果 JS 引擎使用哈希并且没有冲突,最好的情况可能是 O(1))。 这取决于 JS 引擎通常如何实现关联数组/对象,但你可以确保它会击败 O(n)。

因此,第二种方法会更快,但当然会使用更多内存。 这是一个非常典型的权衡,获得更快的速度,但使用更多的内存,并且仅您可以决定是否要进行该交易。

The linear search approach has a complexity of O(n), and I think the worst case for the associative array approach is probably O(log n), (the best case maybe O(1) if the JS engine is using hashes and getting no collisions). It will depend on how a JS engine typically implements associative arrays/objects, but you can be sure it will beat O(n).

So, the second approach will be faster, but will of course use more memory. This is a very typical trade off, gaining more speed, but using more memory, and only you can decide whether you want to make that trade.

尤怨 2024-07-22 04:32:48

考虑需要存储的键值对的数量也很重要。 如果它小于~50(取决于实现),那么由于计算哈希值和解决冲突的成本,执行线性搜索将与执行哈希表查找一样有效。 一个例外是 Google Chrome v8 JavaScript 引擎保留了所有对象的某种缓存版本,允许它直接查找对象上的属性,因此使用 Object 类作为哈希表可能会更快,尽管我不确定创建此缓存版本的成本是否会超过较小列表的好处。

It is also important to consider the number of key value pairs you will need to store. If its less than ~50 (depending on implementation) then doing a linear search will be as efficient as doing a hash table lookup, because of the cost of calculating the hash value and resolving collisions. An exception is the Google chrome v8 JavaScript engine keeps a sort of cached version of all objects that allow it to perform a direct lookup of a property on an object, therefore the use of the Object class as a hash table may be faster, though I'm not sure if the cost of creating this cached version will outweigh the benefit for smaller lists.

眼中杀气 2024-07-22 04:32:48

您可以在第一个方法中使用 Array 的 indexOf 函数。

以下是来自 Mozilla 开发者的信息:
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference: Objects:Array:indexOf

indexOf 是 ECMA-262 标准的 JavaScript 扩展; 因此,它可能不会出现在该标准的其他实现中。 您可以通过在脚本开头插入以下代码来解决此问题,从而允许在本机不支持的 ECMA-262 实现中使用 indexOf。 该算法正是 Firefox 和 SpiderMonkey 中使用的算法。

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
   };
}

You can use the indexOf function of Array in your first method.

Below is the information from Mozilla Developer:
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf

indexOf is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one used in Firefox and SpiderMonkey.

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
   };
}
檐上三寸雪 2024-07-22 04:32:48

Javascript 数组可以使用诸如标题“why-birds-fly”之类的值作为索引。

示例:
var title = "为什么鸟会飞";

var TitleArray[] = new Array();

TitleArray[标题] = id;

然后你可以通过标题直接访问id:

return TitleArray[title];

Javascript arrays can use a value such as the title "why-birds-fly" for the index.

Exmaple:
var title = "why-birds-fly";

var TitleArray[] = new Array();

TitleArray[title] = id;

Then you have direct access to the id by title:

return TitleArray[title];

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文