Map.prototype.has()不能将数组用作键?

sn1*_*n1b 2 javascript arrays ecmascript-6

如何使Map.has()与数组一起使用?

为什么此示例输出false?

let test = new Map();
test.set(["a", "b"], "hi");

console.log(test.has(["a", "b"]));
Run Code Online (Sandbox Code Playgroud)

Rob*_*sen 5

它不起作用,因为您的两个数组未引用同一对象。数组内容是相同的,但数组本身不相同。

如果您使用同一个对象来设置和检索值,则它将起作用:

let test = new Map();
let key = ["a", "b"];

test.set(key, "hi");

console.log(test.has(key)); // true
Run Code Online (Sandbox Code Playgroud)