TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Why I Like Using Maps (and WeakMaps) for Handling DOM Nodes

91 点作者 joelkesler大约 2 年前

7 条评论

kevincox大约 2 年前
I would argue that all &quot;mapping&quot; structures should use Map these days. Objects should be used only for record&#x2F;struct data with a fixed set of programmer-named keys.<p>I think MDN has a good comparison: <a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Reference&#x2F;Global_Objects&#x2F;Map#objects_vs._maps" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Refe...</a><p>The only real downside of maps is that they don&#x27;t support JSON serialization. However you can fix this pretty easily by using a map with an overridden `toJSON` for serializable keys.<p><pre><code> class StringMap extends Map { toJSON() { return Object.fromEntries(this); } }</code></pre>
评论 #35836674 未加载
评论 #35839036 未加载
评论 #35839687 未加载
评论 #35837103 未加载
akira2501大约 2 年前
Why not just use the &#x27;dataset&#x27; property of the element itself? Then you can use querySelectorAll to find your selected rows automatically:<p><pre><code> node.querySelectorAll(&#x27;tr[data-selected=&quot;true&quot;]&#x27;); </code></pre> In other words.. &quot;use the DOM to handle the DOM.&quot;
评论 #35836602 未加载
geuis大约 2 年前
This might be one of the more interesting articles I&#x27;ve read in a few years that deal with low level direct DOM manipulation vs &quot;yet another thing about React&quot;.
评论 #35836003 未加载
globalise83大约 2 年前
Nice! I have used Maps often for storing arbitrary key-value pairs, but until 5 minutes ago I didn&#x27;t know you could use object references as keys. So this was a very good use of 5 mins.
评论 #35838845 未加载
rektide大约 2 年前
I need to read &amp; consider this more, but my word, putting data <i>in</i> the DOM is so divine, is so the web way. See, HTML is the Web, <a href="https:&#x2F;&#x2F;www.petelambert.com&#x2F;journal&#x2F;html-is-the-web" rel="nofollow">https:&#x2F;&#x2F;www.petelambert.com&#x2F;journal&#x2F;html-is-the-web</a>
评论 #35839981 未加载
JoeSloth大约 2 年前
This is great for some use cases, but in situations like a very large list mentioned in the article it’s likely that a real world app would be virtualizing the nodes.. which would make an id a more stable key than a dom node.
eviks大约 2 年前
Why did they not make the map assigning syntax as convenient as with objects, instead going for the clunky get&#x2F;set?
评论 #35839017 未加载
评论 #35839139 未加载