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

如果我的键值是像本示例这样的对象,如何从映射对象获取键值?


const map1 = new Map();

map1.set({x:0,y:0}, 'val');


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

//output: undefined

我正在创建一个键值的地图 key 是一个点,一个 x 和 y 点的对象 val 是一个生物,因为这个原因等于“测试”。我需要在代码中更改什么才能从该关键对象获取该测试值?


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())


ITMISS
浏览 67回答 1
1回答

大话西游666

它必须是一个与键相比相等性为真的对象,而不仅仅是恰好具有相同结构和值的任何对象。例如:a = {x:0,y:0};b = {x:0,y:0};console.log(a == b); // false因此,您需要将关键对象保存在某处并使用它:const map1 = new Map();var key = {x:0,y:0};map1.set(key, 'val');console.log(map1.get(key)); // "val"或者使用其他具有更方便的相等语义的东西作为键。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript