简体   繁体   English

Javascript-顺序数组状对象

[英]Javascript - sequencial array-like object

There are often some tasks like adding items into shopping cart. 通常有一些任务,例如将项目添加到购物车中。 If the cart is an array, it will take O(n) to retrieve an item by id. 如果购物车是一个数组,则需要O(n)才能通过ID检索商品。 It is O(1) using objects, but it then does not guarantee to have the inserting order. 它是使用对象的O(1),但不保证具有插入顺序。

So is there an elegant way to have fast lookup object while maintaining the inserting order? 那么,在保持插入顺序的同时,是否有一种优雅的方法来具有快速查找对象?

I've typically done this by having an array and an object that both reference the same object. 我通常通过使两个数组一个对象都引用同一对象来完成此操作。 Eg: 例如:

var thingies = [];
var thingiesById = Object.create(null);

when adding a "thingy": 添加“东西”时:

thingies.push(thingy);
thingiesById[thingy.id] = thingy;

Example: 例:

 var thingies = []; var thingiesById = Object.create(null); function addThingy(thingy) { thingies.push(thingy); thingiesById[thingy.id] = thingy; } // Note intentionally not adding them in ID order addThingy({id:3, name: "Thingy 3"}); addThingy({id:1, name: "Thingy 1"}); addThingy({id:2, name: "Thingy 2"}); thingies.forEach(function(thingy) { console.log(thingy.id + ": " + thingy.name); }); 


ES2015+'s Map s maintain insertion order and provide iteration semantics that follow that order. ES2015 +的Map维护插入顺序,并提供遵循该顺序的迭代语义。 You'll want to test that lookup speed on get is as good as you need it to be. 您需要测试get上的查找速度是否符合您的要求。

Example: 例:

 const thingies = new Map(); function addThingy(thingy) { thingies.set(thingy.id, thingy); } // Note intentionally not adding them in ID order addThingy({id:3, name: "Thingy 3"}); addThingy({id:1, name: "Thingy 1"}); addThingy({id:2, name: "Thingy 2"}); for (const thingy of thingies.values()) { console.log(thingy.id + ": " + thingy.name); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM