在我的应用程序中,我需要每个日期的对象图。由于打字稿既有个对象Map
又有个Date
对象,所以我希望这很容易。
let map: Map<Date, MyObject> = new Map<Date, MyObject>();
并用于set
添加新的键和值对。但是后来我意识到get
,除非使用完全相同的实例,否则不能使用日期值Date
。
我已经用它编写了一个单元测试:
it('Should not be a problem', () => {
let d1: Date = new Date(2019, 11, 25); // Christmas day
let d2: Date = new Date(2019, 11, 25); // Same Christmas day?
let m: Map<Date, string> = new Map<Date, string>();
m.set(d1, "X");
expect(m.get(d1)).toBe("X"); // <- This is OK.
expect(m.get(d2)).toBe("X"); // <- This test fails.
});
为什么除非使用完全相同的实例,否则无法从映射中获取值?
这是的核心逻辑Map
,正如您所知,映射将值存储在键值对中。
为了比较按键,按键应始终具有相同的参考。如您所知,字符串文字引用在许多编程语言中是相等的,因此,首选使用string作为map中的键。
上面的行为不仅date
适用于任何其他可变对象类型,而且适用于任何其他可变对象类型。
例如
let str1 = 'test';
let str2 = 'test';
str1 == str2; // true
let str1 = new String('test');
let str2 = new String('test');
str1 == str2; // false
从中获取价值时map
,不考虑密钥数据,而是密钥的唯一标识是search。而且,当您创建不可变对象时,每个对象可能具有相同的数据,但是每个对象的引用将不同。因此,它将被视为不同的键。
解决方案是在整个程序中具有相同引用的使用类型,例如字符串文字。
再举一个例子
class Demo {
field: string;
constructor(f: string) {
this.field = f;
}
}
const d1 = new Demo('test');
const d2 = new Demo('test');
// both objects seems same by data, but there references are different
// hence will be treated as separate keys.
const m: Map<any, string> = new Map<any, string>();
m.set(d1, 'value1');
console.log(m.get(d1)); // value1
console.log(m.get(d2)); // undefined
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句