【发布时间】:2016-08-17 07:40:45
【问题描述】:
我正在使用 ES6 Map 对象,其中键是符号、数字或字符串。我选择 map over array 是因为我经常按 key 搜索项目,并且不想每次需要查找 key 时都遍历 array。它也适合我的键值模式。
还会有很多我需要下一个和上一个项目的操作,
偶尔是第一次和最后一次。
基本上它代表表格的表格。
目前我使用:
- next:遍历
Map.keys(),直到找到当前并返回下一个 - 上一页:遍历
Map.keys()记住最后一个键,找到当前返回最后一个键 - 第一:
Map.keys().next().value - 最后:
Array.from(this._data.keys()).reverse()[0];
最后的其他想法是:
let lastKey: any; //I am using TypeScript with "noImplicitAny": true
for (lastKey of map.keys()) { }
哪个更好?
还有其他可能的解决方案吗?我也在考虑创建具有数组和映射的新对象,但这似乎很多或可能没有?像这样的:
class MapArray
{
map = new Map<string | number | symbol, number>(); //map between keys and array indexes
array: Array<any> = [];
constructor(data: Array<any>)
{
for (const d in data)
{
this.add(d);
}
}
add(value: any)
{
this.array.push(value);
this.map.set(Symbol(), this.array.length - 1);
}
next(currentKey: symbol)
{
const current = this.map.get(currentKey);
if (typeof current !== "undefined")
{
if (current >= this.array.length - 1)
return null; //current is last item
return this.array[current + 1];
}
return this.array[0]; //return first
}
previous(currentKey: symbol)
{
const current = this.map.get(currentKey);
if (typeof current !== "undefined")
{
if (current == 0)
return null; //current is first item
return this.array[current - 1];
}
return this.array[this.array.length - 1]; //return last
}
get(key: symbol)
{
const index = this.map.get(key);
if (typeof index !== "undefined")
return this.array[index];
return null;
}
set(key: symbol, value: any)
{
const index = this.map.get(key);
if (typeof index !== "undefined")
this.array[index] = value;
else
this.add(value);
}
//TODO write delete
//TODO write first/last
//TODO write generator
}
你怎么看?数据通常是小数组(20 项具有 3 个属性的对象)或具有大数据的更大数组(1000 项具有 100 个或更多属性的对象)。
代码将主要在移动设备上运行,因此内存使用和性能很重要。
【问题讨论】:
-
结构中的对象有多少属性并不重要。
-
"最后的其他想法" ...好多了。它不需要实例化数组或移动东西 (
reverse)。当然,它仍然非常低效,但至少在内存上没有。 -
你真的需要
delete吗?并且:这种情况经常发生吗? -
尚不确定是否删除。我们会看到项目何时增长,但目前不需要删除方法。
-
那么您的
MapArray确实是最好的解决方案。
标签: javascript arrays dictionary ecmascript-6