如何将代码改写为ES6箭头函数?含随机颜色生成器代码优化需求
问题1:如何使用ES6箭头函数编写指定代码块?
箭头函数是ES6带来的简洁写法,核心用=>替代传统function关键字,不同场景的写法可以参考下面的例子:
无参数函数:需要用空括号
()开头,如果只有一行执行语句,还能省略大括号// 普通函数写法 function greet() { console.log("Hey there!"); } // 箭头函数写法 const greet = () => console.log("Hey there!"); // 多行逻辑的话要加大括号 const greet = () => { const message = "Hey there!"; console.log(message); };单个参数函数:单个参数可以省略括号,直接写参数名
// 普通函数 function square(num) { return num * num; } // 箭头函数(一行返回可省略大括号和return) const square = num => num * num;多个参数函数:多个参数必须用括号包裹
// 普通函数 function multiply(a, b) { return a * b; } // 箭头函数 const multiply = (a, b) => a * b;
要注意的是,箭头函数没有自己的this、arguments对象,也不能当作构造函数使用,这些特性要结合实际场景判断是否适用。
问题2:简化随机颜色生成器并转换为ES6箭头函数
先看你的原代码,里面的red、green、blue参数其实没起到作用(每次循环都会重新赋值),而且document.write不太推荐(容易覆盖页面原有内容),我帮你重构并改成箭头函数版本:
简化后的箭头函数实现
// 生成单个0-255的随机颜色值 const getRandomColorVal = () => Math.floor(Math.random() * 256); // 生成随机RGB颜色字符串 const getRandomRgb = () => `rgb(${getRandomColorVal()}, ${getRandomColorVal()}, ${getRandomColorVal()})`; // 生成10个颜色块并插入页面 const generateColorBlocks = () => { // 用数组map生成色块字符串,比循环拼接更简洁 const blocks = Array.from({ length: 10 }, () => `<div style="background-color: ${getRandomRgb()}; width: 100px; height: 100px; display: inline-block; margin: 5px;"></div>` ).join(''); // 把色块插入body(也可以指定页面中的某个容器) document.body.innerHTML += blocks; }; // 调用生成函数 generateColorBlocks();
重构说明:
- 拆分功能:把生成单个颜色值、生成RGB字符串、生成色块的逻辑拆成独立箭头函数,代码更清晰易维护;
- 移除无用参数:原函数的
red、green、blue参数没有实际作用,直接删除; - 替换document.write:用
innerHTML插入色块,避免覆盖页面原有内容; - 简化循环逻辑:用
Array.from结合map生成色块数组,再拼接成字符串,比传统for循环写法更简洁; - 补充基础样式:给色块加了宽高、间距、行内块样式,确保能正常显示。
如果你还是喜欢用for循环,也可以写成这样:
const generateColorBlocks = () => { let html = ""; for (let i = 0; i < 10; i++) { html += `<div style="background-color: ${getRandomRgb()}; width: 100px; height: 100px; display: inline-block; margin: 5px;"></div>`; } document.body.innerHTML += html; };
内容的提问来源于stack exchange,提问作者Harman Pannu
相关产品推荐
相关产品推荐

