为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2023-07-06 14:49:13
如果我的键值是像本示例这样的对象,如何从映射对象获取键值?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())
查看完整描述

1 回答

?
大话西游666

TA贡献1817条经验 获得超14个赞

它必须是一个与键相比相等性为真的对象,而不仅仅是恰好具有相同结构和值的任何对象。


例如:


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"

或者使用其他具有更方便的相等语义的东西作为键。


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信