我有一个长度为 N 的数组。我需要创建一个重复序列的新数组。新数组将具有对应于 N 数组中的条目的子集数组,例如:
N0 = [1,0,0]
N1 = [0,1,0]
N2 = [0,0,1]
N3 = [1,0,0]
N4 = [0,1,0];
reapeat...
预期输出: [[1,0,0],[0,1,0],[0,0,1],[1,0,0][0,1,0][0,0,1], repeating...]
我在如何做到这一点上画了一个空白我的第一个想法是在每个元素的索引上使用模运算符
positions = [[98,8097,709], [8,907,098], [234,543w6,098], [098,087,08089], "LOL", {cool: bro}, function(){console.log(derp);}]
positions.map((pos, idx) => {
if(idx % 1){
return [1,0,0];
}
if(idx % 2){
return [0,1,0];
}
if(idx % 3){
return [0,0,1];
}
})
使用new Array(length).fill(0)
您的map()
再利用模设置1
let positions = [
[98, 8097, 709],
[8, 907, 098],
[234, '543w6', 098],
[098, 087, 08089], "LOL", {
cool: 'bro'
},
function() {
console.log('derp');
}
]
let res = positions.map((pos, idx) => {
let subArr = new Array(3).fill(0)
subArr[idx % 3] = 1
return subArr
})
console.log(res)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句