Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何动态构建javascript对象并将其推入嵌套循环中的数组?_Javascript_Arrays_Object_Matrix_Mapping - Fatal编程技术网

如何动态构建javascript对象并将其推入嵌套循环中的数组?

如何动态构建javascript对象并将其推入嵌套循环中的数组?,javascript,arrays,object,matrix,mapping,Javascript,Arrays,Object,Matrix,Mapping,我试图动态地构建对象,并将它们一个接一个地推送到一个数组中 到目前为止,我的代码是: matrix([[0,1,1], [1,00], [1,1,1]) const matrix = (sequence) => { const rows = {} const rowsAry = [] let row let idx for (let i=0; i < samples.length; i++) { row = `row${i}`

我试图动态地构建对象,并将它们一个接一个地推送到一个数组中

到目前为止,我的代码是:

matrix([[0,1,1], [1,00], [1,1,1])

const matrix = (sequence) => {
   const rows = {}
   const rowsAry = []
   let row
   let idx
  
   for (let i=0; i < samples.length; i++) {
       row = `row${i}`
    
       for (let j=0; j < samples[i].length; j++) {
          if (samples[i][j] === 1) {
               idx = []
               rows[row] = rows[row] + 1 || 1 
               rows['indeces'] = idx.push(j)  
               rowsAry.push(rows)
            }
            
        }
    }
    console.log(rowsAry)

}
希望的产出将是:

[{row1: 2, indices: [1,2]}, 
 {row2: 1, indices: [0]}, 
 {row3: 3, indices: [0,1,2]}
] 


每次通过外循环时都需要创建一个新对象。只需将其推到
行上一次,而不是每次通过内部循环

const矩阵=(示例)=>{
const rowsAry=[]
for(设i=0;i])
您可以通过简单地使用数组mapforEach方法来解决它。遍历数组数组,使用array-forEach方法检查数组内部的数组,如果找到,则将其放入结果数组。最后,使用生成的数组生成所需的对象

const矩阵=(序列)=>{
返回序列.map((x,i)=>{
常数ret=[];
x、 forEach((y,j)=>{
如果(y==1)反向推力(j);
});
const key=`row${i+1}`;
const obj={[key]:ret.length,索引:ret};
返回obj;
});
};
常数ret=矩阵([
[0, 1, 1],
[1, 0, 0],
[1, 1, 1],
]);
控制台日志(ret)或嵌套的
reduce()
调用

const矩阵=(序列)=>{
返回序列.reduce((a,r,i)=>{
指数=r.reduce((ra,rn,ri)=>{
如果(rn==1)拉压(ri);
返回ra;
}, []);
a、 push({[`row${i}`]:index.length,index:index});
返回a;
}, []);
}

log(矩阵([[0,1,1],[1,0,0],[1,1,1]])
为什么在每个对象中使用不同的
rowX
键?在
示例上循环。不应该是序列吗?是的,你是对的。
[{row1: 2, indices: [1,2]}, 
 {row2: 1, indices: [0]}, 
 {row3: 3, indices: [0,1,2]}
]