javascript 循环数组,彩虹文本练习

tnkciper  于 2022-12-17  发布在  Java
关注(0)|答案(4)|浏览(128)

需要帮助.我附上的图像的问题,这是图像的代码:

// This is the given code:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
// I written these:

const spans = document.querySelector('h1 span');

for(let rainbow of spans){
    spans.style.color = " ";
}
vc6uscn9

vc6uscn91#

您应该使用document.querySelectorAll('h1 span')来获取所有span项。
然后用Array.forEach得到字符和索引,然后把索引Map到colors数组。

// This is the given code:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

// I written these:
const spans = document.querySelectorAll('h1 span');
spans.forEach((item, index) => {
  item.style.color = colors[index];
})
<h1>
  <span>R</span>
  <span>A</span>
  <span>I</span>
  <span>N</span>
  <span>B</span>
  <span>O</span>
  <span>W</span>
</h1>
yruzcnhs

yruzcnhs2#

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; 
//PLEASE DON'T CHANGE THIS LINE!

//YOU CODE GOES HERE:

const letters = document.querySelectorAll('span')enter code here

let count = 0

for (let letter of letters){
    letter.style.color = colors[count]
    count += 1
}
z6psavjg

z6psavjg3#

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!

//YOU CODE GOES HERE:

const allh=document.querySelectorAll('span');
let i=0;
for(let h of allh){
    h.style.color = colors[i++];
    
}
<!DOCTYPE html>

<head>
    <title>Rainbow</title>
    <!--LEAVE THESE LINES ALONE, PLEASE! THEY MAKE THE LIVE PREVIEW WORK!-->
    <script src="node_modules/babel-polyfill/dist/polyfill.js" type="text/javascript"> </script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

</head>

<body>
    <!--DON'T TOUCH THIS FILE PLEASE!-->
    <h1>
        <span>R</span>
        <span>A</span>
        <span>I</span>
        <span>N</span>
        <span>B</span>
        <span>O</span>
        <span>W</span>
    </h1>
</body>

</html>
vyswwuz2

vyswwuz24#

常量颜色=[“红色”、“橙色”、“黄色”、“绿色”、“蓝色”、“靛蓝”、“紫色”];//请不要更改此行!
//您的代码位于此处:假设v =文档.查询选择器全部(“span”)
对于(令i = 0; i〈色长; i++){ v[i].样式.颜色=颜色[i];
}

相关问题