gpt4 book ai didi

javascript - 从 double 'for' 循环中获取所有出现的值的索引

转载 作者:行者123 更新时间:2023-11-30 11:08:21 27 4
gpt4 key购买 nike

首先,如果标题不够精确,请随意修改。

JS完全不是我的地盘。我正在尝试编写这个自定义 JS 回调,除了索引抓取行之外,它可以满足我的要求。但是,由于我已经在双 for 循环中,所以我不知道如何正确推送

(正确的意思是:在推送到“partial_data”var 之前,“active holder”var 中出现的每个值所在的索引)

索引到索引变量。现在看来,它只会返回第一次出现的索引。

var full_data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var partial_data = []
var active_holder = ['a', 'g']
var indexes = []

for (j = 0; j < full_data.length; j++) {

for (z = 0; z < active_holder.length; z++) {

if (active_holder[z].includes(full_data[j])) {

indexes.push(full_data.indexOf(full_data[j]));
partial_data.push(full_data[j]);
}
}
}

console.log(partial_data) // * ['a', 'a', 'g', 'g'] //
console.log(indexes) // * [0, 0, 5, 5] // WRONG, should be 0,4,5,6 or something along

有什么建议吗?

最佳答案

您可以使用 reduceincludes

const fullData = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
const active = ['a', 'g']

let {partial, index} = fullData.reduce((op,inp,index)=>{
if( active.includes(inp) ){
op.partial.push(inp)
op.index.push(index)
}
return op
},{partial:[],index:[]})

console.log(partial)
console.log(index)

关于javascript - 从 double 'for' 循环中获取所有出现的值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54771125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com