Insert from list into array

匿名 (未验证) 提交于 2019-12-03 02:35:01

问题:

I wanted to know how I can return an array of names currently on the leaderboard.

This is the code I have:

function top10(maximumResults) {   //store the leaderboard elements   //check if leaderboard is less than 10   //loop through leaderboard   //return   var output2 = document.getElementById("top10").getElementsByTagName("li");   var output = "";    for(var i = 0; i < output2.length; i++) {     if(maximumResults.length < 10) {       output[i] += output2[i].id;     }   }     return output; }
<div id=leaderboard class=panel>   <h1>Leaderboard</h1>   <ol id=top10>     <li>test</li>     <li>aaadad</li>     <li>dfghfdh</li>     <li>dfghdfhg</li>     <li>dfghfdh</li>   </ol> </div>

回答1:

You can fetch the li values into an array with this line of code:

return Array.from(document.querySelectorAll('#top10>li'), li => li.textContent) 

If the intention is to limit that result array to maximumResults elements, then you can use slice:

return Array.from(document.querySelectorAll('#top10>li'), li => li.textContent)             .slice(0, maximumResults) 


回答2:

This could be done with react very easy, but in this case all you need is some jquery!:

var array = [1, 2, 4, 5, ,6 ,7 ,8] /// here you can update with own elements  $(document).ready(function() {     for (var i = 0; i < array.length; i++) {          $("ol").append("<li>" + array[i] + "</li>")          }   }) 

Demo here: http://jsfiddle.net/n5phf/405/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!