Vanilla JS技术问题:如何用map遍历字符串数组设置按钮innerHTML?
问题解答
首先明确:可以用map()实现,但map()的设计初衷是转换数组生成新数组,并非执行赋值这类副作用操作,因此更推荐使用forEach()来完成遍历赋值的需求。
你的代码问题出在哪?
document.getElementsByTagName("button")返回的是HTMLCollection类数组对象,不是单个按钮元素,直接给它赋值innerHTML是无效操作,浏览器最终只会保留最后一次循环的赋值结果。- 循环中没有关联数组元素和对应位置的按钮,每次都在尝试给整个按钮集合设置内容,自然只会显示最后一个数组元素。
解决方案
方案1:用map()实现(满足你的需求)
通过数组索引关联数组元素和对应按钮,同时做越界判断避免报错:
var buttons = document.getElementsByTagName("button"); const a = ["click for more", "see more", "details page", "next >"]; a.map((text, index) => { // 确保当前索引存在对应的按钮 if (buttons[index]) { buttons[index].innerHTML = text; } });
方案2:更合适的forEach()(推荐)
如果不需要生成新数组,forEach()是更贴合场景的选择:
var buttons = document.getElementsByTagName("button"); const a = ["click for more", "see more", "details page", "next >"]; a.forEach((text, index) => { if (buttons[index]) { buttons[index].innerHTML = text; } });
方案3:转成数组后操作(更灵活)
把HTMLCollection转成真正的数组,后续操作更方便:
const buttons = Array.from(document.getElementsByTagName("button")); const a = ["click for more", "see more", "details page", "next >"]; buttons.map((button, index) => { if (a[index]) { button.innerHTML = a[index]; } return button; // map需要返回值,这里返回处理后的按钮 });
内容的提问来源于stack exchange,提问作者Mateusz Szumilo
相关产品推荐
相关产品推荐

