亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果鍵是對象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 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號