Javascript 中用于键值对的 forEach() 方法
如何仅打印显示屏中的值?
let room1 = new Map();
room1.set("candles", 8)
room1.set("fridge", 1)
room1.set("washing machine", 3)
room1.set("chairs", 4)
room1.set("sofa", 2)
room1.set("jacuzzi", 6)
let text4 = "";
room1.forEach(function(key) {
text4 += key + "<br>"
});
document.getElementById("demo8").innerHTML = text4;
<p id="demo8"></p>
How to print only the value(s) in the display?
let room1 = new Map();
room1.set("candles", 8)
room1.set("fridge", 1)
room1.set("washing machine", 3)
room1.set("chairs", 4)
room1.set("sofa", 2)
room1.set("jacuzzi", 6)
let text4 = "";
room1.forEach(function(key) {
text4 += key + "<br>"
});
document.getElementById("demo8").innerHTML = text4;
<p id="demo8"></p>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
现在是 2022 年。忘记
forEach
并使用针对...的
。它在迭代Map
时获取键值对:It's 2022. Forget
forEach
and usefor...of
. It gets key-value pairs when iterating over aMap
:有一些解决方案,请遵循四种可能性...
1) 对于 更好的性能 使用
for...of
代替forEach
:2) 短代码(扩展语法)到获取
Map
的keys
并转换为Array
:3) 与第一个解决方案相同,但使用
Array.from(...)
显式:4) 将第一个参数
value
添加到forEach
函数:示例:
参考:
如何在地图上使用 .map() Javascript 中的键
https://www.geeksforgeeks.org/javascript-map-foreach-method/
There're some solutions, follow four possibilities...
1) For a better performance use
for...of
insteadforEach
:2) Short code (spread syntax) to get the
keys
of yourMap
and convert toArray
:3) The same of first solution but with
Array.from(...)
explicit:4) Add the first parameter
value
toforEach
function:Example:
Reference:
How to use .map() over Map keys in Javascript
https://www.geeksforgeeks.org/javascript-map-foreach-method/
您只能直接获得钥匙。
You could get only the keys directly.