javascript - 从列表插入数组

标签 javascript html

我想知道如何返回当前排行榜上的名称数组。

这是我的代码:

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>

最佳答案

您可以使用以下代码行将 li 值提取到数组中:

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

如果目的是将结果数组限制为 maximumResults 元素,那么您可以使用 slice:

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

关于javascript - 从列表插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40390298/

相关文章:

html - 在网站上嵌入 3D 模型

html - 图像叠加层中的中心 CSS 'content' 属性

css - 如何阻止我的 2 列布局将右侧的 float div 推到下方?

javascript - Chrome 调整大小事件和 getComputedStyle

javascript - 在 Javascript 中选中复选框时显示消息

javascript - jquery datepicker 多个输入

javascript - 单引号比双引号快?

php - 用于在网页中解析的大型数据集

javascript - 在 chrome 中为 console.table() 添加样式

jquery - 通过鼠标悬停更改形状的颜色?