猿问

具有不同索引的数组的输出元素

我有一张桌子。当我单击一个元素时,我返回它的索引。我怎样才能(从这个元素开始)显示索引+ 9的所有元素。即如果所选元素的索引为0,那么我还需要显示索引为9、18、27等的元素。


let newCell = [td#2, td#0, td#2, td#0, td#2, ..... td#1, td#0]


newCell.forEach((item, i) => {

    item.addEventListener('click', () => {   

        console.log(i)

    })

})


慕桂英3389331
浏览 105回答 2
2回答

交互式爱情

在这种情况下,您需要做的是跟踪应过滤掉哪些元素的计数,然后在过滤时更新该计数。不幸的是,我不清楚你的细胞数据,所以我继续做出自己的解释。let data = [];for (let i = 0; i < 100; i++) {&nbsp; &nbsp; data.push({ id: i });}function getByNine(id) {&nbsp; &nbsp; let count = id + 9&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return data.filter(i => {&nbsp; &nbsp; &nbsp; &nbsp; if (i.id === count) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count = count + 9&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}console.log(getByNine(3))getByNine(i)在事件侦听器中,您可以放置对函数(或任何您想要调用它的名称)的引用并传递其索引。在此函数中,您设置默认计数 9 + 无论单击的元素的 id 是什么对对象数组运行过滤器,当计数正确时返回该项目,然后将计数增加 9 以获取下一个正确的元素function getByNine(i) {&nbsp; &nbsp;// code here}newCell.forEach((item, i) => {&nbsp; &nbsp; item.addEventListener('click', () => {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; getByNine(i)&nbsp; &nbsp; })})

Qyouu

我没有包含“显示”该系列中将出现的那些元素的代码,但下面是记录它们的代码。您可以更新它以显示它们。const DIFF = 9;newCell.forEach((item, i) => {&nbsp; &nbsp; item.addEventListener('click', ()=>logAllItemsInSeries(i));}const logAllItemsInSeries = (i) => {&nbsp; &nbsp; console.log(i);&nbsp; &nbsp; const series = [];&nbsp; &nbsp; while (i < newCell.length) {&nbsp; &nbsp; &nbsp; &nbsp; series.push(i);&nbsp; &nbsp; &nbsp; &nbsp; i += DIFF;&nbsp; &nbsp; }&nbsp; &nbsp; series.forEach((index) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(index);&nbsp; &nbsp; &nbsp; &nbsp; console.log(newCell[index]);&nbsp; &nbsp; });};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答