Typescript/Javascript:使用元组作为Map的键

24

在我的代码中遇到了一个奇怪的 bug,我无法想出一种方法使得使用元组作为键时可以从 Map 中进行常数时间查找。

希望这能说明问题,以下是我现在使用的解决方法:

hello.ts:

let map: Map<[number, number], number> = new Map<[number, number], number>()
    .set([0, 0], 48);

console.log(map.get([0,0])); // prints undefined

console.log(map.get(String([0, 0]))); //  compiler:  error TS2345: Argument of type 
// 'string' is not assignable to parameter of type '[number, number]'.

//the work-around:
map.forEach((value: number, key: [number, number]) => {
    if(String(key) === String([0, 0])){
        console.log(value); // prints 48
    }
})

我使用以下工具进行编译(转换?):

tsc hello.ts -target es6

tsc版本为2.1.6

尝试了几种方法使Map.get()方法正常工作,但没有太大的成功。

4个回答

41
在JavaScript(以及作为扩展的TypeScript)中,除非两个数组引用相同的数组(即更改一个数组的元素也会更改另一个数组的元素),否则没有两个数组是相等的。如果您使用相同的元素创建一个新数组,则不会将其视为与任何现有数组相等。
由于Map在查找元素时考虑这种相等性,如果您将带有数组作为键的值存储,那么只有在再次传递完全相同的数组引用作为键时,您才能再次获取该值:
const map: Map<[ number, number], number> = new Map<[ number, number ], number>();

const a: [ number, number ] = [ 0, 0 ];
const b: [ number, number ] = [ 0, 0 ];

// a and b have the same value, but refer to different arrays so are not equal
a === b; // = false

map.set(a, 123);
map.get(a); // = 123
map.get(b); // = undefined

解决这个问题的一个简单方法是使用字符串或数字作为键,因为当它们具有相同的值时总是被视为相等:


const map: Map<string, number> = new Map<string, number>();

const a: [ number, number ] = [ 0, 0 ];
const b: [ number, number ] = [ 0, 0 ];

const astr: string = a.join(','); // = '0,0'
const bstr: string = b.join(','); // = '0,0'

// astr and bstr have the same value, and are strings so they are always equal
astr === bstr; // = true

map.set(astr, 123);
map.get(astr); // = 123
map.get(bstr); // = 123

完全明白。谢谢! - ZackDeRose
3
元信息:有一个网站,直接将评论列表抄袭为“博客文章”而没有进行适当的归属证明:https://newbedev.com/typescript-javascript-using-tuple-as-key-of-map -- 看起来非常不正当。 - a p

10
我会创建自己的类来实现这个功能,以便我可以轻松使用所有的地图方法:
class MyMap {
    private map = new Map<string, number>();

    set(key: [number, number], value: number): this {
        this.map.set(JSON.stringify(key), value);
        return this;
    }

    get(key: [number, number]): number | undefined {
        return this.map.get(JSON.stringify(key));
    }

    clear() {
        this.map.clear();
    }

    delete(key: [number, number]): boolean {
        return this.map.delete(JSON.stringify(key));
    }

    has(key: [number, number]): boolean {
        return this.map.has(JSON.stringify(key));
    }

    get size() {
        return this.map.size;
    }

    forEach(callbackfn: (value: number, key: [number, number], map: Map<[number, number], number>) => void, thisArg?: any): void {
        this.map.forEach((value, key) => {
            callbackfn.call(thisArg, value, JSON.parse(key), this);
        });
    }
}

(let map = new MyMap(); map.set([1, 2], 4); console.log(map.get([1, 2])) // 4 map.set([3, 4], 20); map.forEach((v, k) => console.log(k, v)); // prints: // [1, 2] 4 // [3, 4] 20


1
还有一个http://www.collectionsjs.com/,你可以覆盖contentEquals和contentHash方法来确定键等效性。 - Franck Valentin

4
在某些情况下(例如,当元组中的第二个值取决于第一个值时),我认为可以使用嵌套的映射来代替:
// situation: a map from a tuple of (tableId, rowId) to the row's title

// instead of Map<[number, number], string> where the first number is
// tableId and the second number is rowId, we can have:
const rowTitleMap = Map<number, Map<number, string>>

const title = rowTitleMap.get(2)?.get(4) // can be string or undefined

1

我不知道这是否适用于Typescript,或者是否存在其他缺点,但对我来说,这似乎是一种简单易用的方法,将保留键作为元组:

const key_map_key_string = (tuple) => JSON.stringify(tuple);

const string_identical_tuple_key = (map_for_keying = new Map()) => {
  let key_map = new Map();
  [...map_for_keying.keys()].forEach((key) => key_map.set(key_map_key_string(key), key));

  return (tuple) => {
    const res = key_map.get(key_map_key_string(tuple));
    if(res) return res;

    key_map.set(key_map_key_string(tuple), tuple);
    return tuple;
  };
};

const test = () => {
  let a_map = new Map([
    [[1, 2], 'value1'],
    [[3, 4], 'value2']
  ]);
  
  const get_key = string_identical_tuple_key(a_map);
  
  console.log(a_map.get( get_key([1, 2]) ) === 'value1');
  
  a_map.set(get_key([5, 6]), 'value3');
  
  console.log(a_map.get( get_key([5, 6]) ) === 'value3');
  
  a_map.set(get_key([3, 4]), 'value4');
  
  console.log(JSON.stringify([...a_map]));
};

test();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接