简体   繁体   English

如果键是对象js,如何从映射中的键获取值

[英]how to get value from key in map if key is an object js

How can I get a key value from a map object if my key value is an object like this example?如果我的键值是像这个例子这样的对象,我如何从地图对象中获取键值?

const map1 = new Map();
map1.set({x:0,y:0}, 'val');

console.log(map1.get({x:0,y:0}));
//output: undefined

I am creating a map of a key value key is a point an object of x and y points val is a creature from this reason is equals to 'test'.我正在创建一个键值的映射键是一个点 x 和 y 点的对象 val 是一个生物,因为这个原因等于“测试”。 What I need to change in my code to get this test value from this key object ?我需要在我的代码中更改什么才能从这个关键对象中获取这个测试值?

class Board {
    constructor() {
        this.map = new Map();
    }
    add(point, creature) {
        this.map.set(point, creature)

    }
    getVal(aX, aY) {
        console.log(this.map) // Map { Point { x: 0, y: 0 } => Creature {} }
        console.log(new Point(aX, aY)) //output: {x:0,y:0}
        console.log(this.map.get(new Point(aX, aY))) //output: undefined
        return this.map.get(new Point(aX, aY))
    }
}

class Point {
    constructor(aX, aY) {
        this.x = aX;
        this.y = aY;
    }
}

function test() {
    let board = new Board();
    board.add(new Point(0, 0), 'test');

    return cretureFromBoard = board.getVal(0, 0);
}
console.log('test()', test())

It needs to be an object whose equality is true when compared to the key, not just any object that happens to have the same structure and values.它需要是一个与键相比相等的对象,而不仅仅是任何碰巧具有相同结构和值的对象。

For example:例如:

a = {x:0,y:0};
b = {x:0,y:0};
console.log(a == b); // false

So you would need to keep your key object somewhere and use that:所以你需要把你的关键对象放在某个地方并使用它:

const map1 = new Map();
var key = {x:0,y:0};
map1.set(key, 'val');

console.log(map1.get(key)); // "val"

Or use something else, with more convenient equality semantics, for the key.或者使用其他更方便的相等语义的东西作为键。

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

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