问题描述
看看几个不同的文档,我所看到的只是Map(ECMAScript6)键是布尔值,字符串还是整数.有没有一种方法可以使用另一个自定义对象(通过新的CustomObject(x,y)构造函数调用)作为键添加?
Looking at a couple of different docs, all I see is when the Map (ECMAScript6) key is a boolean, string, or integer. Is there a way we could use another customized Object (called with the new CustomObject(x,y) constructor call) to be added as a key?
我能够添加一个对象作为键,但是无法检查Map是否具有所述对象.
I am able to add an object as a key, but unable to check if the Map has the said object.
var myMap = new Map();
myMap.set( new Tuple(1,1), "foo");
myMap.set('bar', "foo");
myMap.has(?);
myMap.has('bar'); // returns true
有没有解决的办法?
var myMap = new Map();
myMap.set( new Tuple(1,1), "foo");
for(some conditions) {
var localData = new Tuple(1,1); //Use directly if exists in myMap?
map.has(localData) // returns false as this is a different Tuple object. But I need it to return true
}
https://developer.mozilla. org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map/has
推荐答案
您只需要保存对该对象的引用:
You just have to save the reference to the object:
var myMap = new Map();
var myKey = new Tuple(1,1);
myMap.set( myKey, "foo");
myMap.set('bar', "foo");
myMap.has(myKey); // returns true; myKey === myKey
myMap.has(new Tuple(1,1)); // returns false; new Tuple(1,1) !== myKey
myMap.has('bar'); // returns true; 'bar' === 'bar'
这是如何使用对象来实现所需的方法,即通过对象的值而不是引用来比较对象:
Here is how to use an object to achieve what you want, which is to compare objects by their values rather than by reference:
function Tuple (x, y) {
this.x = x;
this.y = y;
}
Tuple.prototype.toString = function () {
return 'Tuple [' + this.x + ',' + this.y + ']';
};
var myObject = {};
myObject[new Tuple(1, 1)] = 'foo';
myObject[new Tuple(1, 2)] = 'bar';
console.log(myObject[new Tuple(1, 1)]); // 'foo'
console.log(myObject[new Tuple(1, 2)]); // 'bar'
这些操作平均会在恒定时间内运行,这比在线性时间内在地图上搜索相似的对象键要快得多.
These operations will run in constant time on average, which is much faster than searching through a Map for a similar object key in linear time.
这篇关于如何检查Javascript Map是否具有对象密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!