Javascript中的WeakMap

时间:2018-04-29 16:20:53

标签: javascript ecmascript-6 set weakmap

您能否澄清为什么在下面的代码中将对象添加到WeakMaps时使用boolean。我理解set有两个(键和值)参数。布尔值也会在控制台中打印出来......这是我的疑问......

先谢谢。

const book1 = { title: 'Pride and Prejudice', author: 'Jane Austen' };
const book2 = { title: 'The Catcher in the Rye', author: 'J.D. Salinger' };
const book3 = { title: 'Gulliver\'s Travels', author: 'Jonathan Swift' };

const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);

console.log(library);

WeakMap {Object {title: 'Pride and Prejudice', author: 'Jane Austen'} => true, Object {title: 'The Catcher in the Rye', author: 'J.D. Salinger'} => false, Object {title: 'Gulliver\'s Travels', author: 'Jonathan Swift'} => true}

1 个答案:

答案 0 :(得分:0)

WeakMap不仅仅是存储对象(Set - 与.set不同)。

它在两件事之间建立了关系,即关键和价值。 book1用作值true的键。

就像普通对象var obj = { daysInWeek: 7 }一样,字符串daysInWeek与数字7相关(映射!),因此obj["daysInWeek"] === 7

数组也是类似的 - 数字(索引)映射到值; var arr = [ "praveen" ]将数字0映射到字符串"praveen",以便arr[0] === "praveen"

MapWeakMap是相同的,但键不仅限于字符串或数字,它们也可以是对象。所以library.get( book1 ) === true