繁体   English   中英

如何在ES6箭头功能中编写此代码块

[英]How can I write this block of code in ES6 Arrow Function

我试图创建一个随机颜色生成器是否有任何方法来缩短此代码并转换为es6箭头功能? 谢谢

let html = "";
let rgbColor;

function randomColors(red, green, blue) {
  for (let i = 1; i <= 10; i++) {
    red = Math.floor(Math.random() * 256);
    green = Math.floor(Math.random() * 256);
    blue = Math.floor(Math.random() * 256);
    rgbColor = `rgb(${red},${green},${blue})`;
    html += `<div style="background-color:${rgbColor}"></div>`;
  }

 document.write(html);
}

randomColors()

您可以使用Array#fromArray#join生成每种颜色和颜色列表,并将所有内容组合到一个字符串中:

 const randomColors = (count) => Array.from({ length: count }, (_, k) => // create an array of divs with length of count `<div style="background-color: rgb(${ Array.from({ length: 3 }, () => Math.floor(Math.random() * 256)).join() })">${k}</div>` // inside each div create an array of 3 colors, and join them ).join(''); // join the array of divs to one string document.write(randomColors(9)); 

你可以这样做:

let html = "";
let rgbColor;

let randomColors = (red, green, blue) => {
  for (let i = 1; i <= 10; i++) {
    red = Math.floor(Math.random() * 256);
    green = Math.floor(Math.random() * 256);
    blue = Math.floor(Math.random() * 256);
    rgbColor = `rgb(${red},${green},${blue})`;
    html += `<div style="background-color:${rgbColor}"></div>`;
  }
  document.write(html);
}

randomColors()

但这不会过多地缩短这段代码。

这个答案是准确的,因为它是使用箭头函数的randomColors函数的有效表示。 然而(正如他所指出的),它本身并没有提供缩短代码的方法。 为此,我建议提出一个辅助函数来生成随机颜色(参见下面的getRandColor函数)。

let html = "";
let rgbColor;

const randomColors = (red, green, blue) => {
  const getRandColor = () => Math.floor(Math.random() * 256);

  for (let i = 1; i <= 10; i++) {
    [red, green, blue] = [getRandColor(), getRandColor(), getRandColor()];
    rgbColor = `rgb(${red},${green},${blue})`;
    html += `<div style="background-color:${rgbColor}"></div>`;
  }
  document.write(html);
}

或许尝试以上方法。

较短并不总是最好的。 这很短,但可能有点不透明:

let html = ""

const randomColors=()=>(
    ((rnd)=>(`<div style="background-color: rgb(${rnd()},${rnd()},${rnd()})"></div>`))
    (()=>Math.floor(Math.random()*256))
)

html+=randomColors()
document.write(html)

ES6箭头函数用于替换标准匿名函数,而无需创建函数通常创建的新范围。 所以你的函数将保持其名称,不会是箭头函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM