有人问我这个关于在 ES5 和 ES6 中实现商店的问题。
我一直在尝试解决这个问题,但我一直卡在如何存储节点上
实现商店类:
Implement a store class with set(Node, value ), get(Node) and has(Node) methods, which stores given Nodes with corresponding values.
这就是我能够写的(伪代码)
function Store () {
this.store = [];
}
Store.prototype.set = function(node, v) {
// Problem here would be how do I store the node?
}
Store.prototype.get = function(node) {
if(this.has(node)) {
return this.store.find(each => {
// Check to see if it's the same node and return.
})
}
}
Store.prototype.has = function(node) {
return this.store.indexOf(node) > -1;
}
注意:我们可以在商店中存储 HTML DOM。所以键将是一个“DOM”元素而不是一个字符串。
谁能举个例子启发我?我想这会像 ES6 中的 Map 一样工作。如果我要在 ES5 中实现它,我该如何首先存储 DOM 节点?
最佳答案
在 ES5 时代,创建一个键数组并使用线性搜索定位它们是很常见的。这不是最有效的解决方案,但很简单。
function Store() {
this.keys = [];
this.values = [];
}
Store.prototype.set = function(key, val) {
var i = this.keys.indexOf(key);
if(i < 0) {
i = this.keys.push(key) - 1;
}
this.values[i] = val;
};
Store.prototype.get = function(key) {
return this.values[this.keys.indexOf(key)];
};
Store.prototype.has = function(key) {
return this.keys.indexOf(key) >= 0;
};
//
a = document.querySelector("#a")
b = document.querySelector("#b")
c = document.querySelector("#c")
s = new Store()
s.set(a, '1')
s.set(b, '2')
console.log(s.has(a), s.get(a))
console.log(s.has(b), s.get(b))
console.log(s.has(c), s.get(c))
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
这个解决方案有两个问题:首先,缓慢的线性搜索,其次,也是更重要的,因为 Store 保留对关键对象的引用,一旦销毁它们就不能被垃圾回收。
一个更有效的选择是将键注入(inject)值本身,但这实现起来要棘手得多。
对于 ES6 部分,有一个专门用于此类事情的内置对象,称为 WeakMap
.
关于javascript - 在 JavaScript 中实现节点存储功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55658146/