Javascript 通过复制创建对象数组
编写一个函数,该函数接受以下输入,并通过增加对象的id来复制对象,从而返回一个对象数组(长度为10) 对于输出[0],可见值必须为true;对于剩余值,可见值必须为falseJavascript 通过复制创建对象数组,javascript,arrays,typescript,redux,Javascript,Arrays,Typescript,Redux,编写一个函数,该函数接受以下输入,并通过增加对象的id来复制对象,从而返回一个对象数组(长度为10) 对于输出[0],可见值必须为true;对于剩余值,可见值必须为false input: { id: 0, visible: true, width: 200 ; height: 200; } output: [ { id: 0, visible: true, width: 20
input:
{ id: 0,
visible: true,
width: 200 ;
height: 200;
}
output:
[ { id: 0,
visible: true,
width: 200 ;
height: 200;
},
{ id: 1,
visible: false,
width: 200 ;
height: 200;
},{ id: 2,
visible: false,
width: 200 ;
height: 200;
},{ id: 3,
visible: false,
width: 200 ;
height: 200;
},.
.
.
.
{ id: 9,
visible: false,
width: 200 ;
height: 200;
}]
您可以创建一个10个元素的数组,用
0
填充它(或任何东西,填充只是启用迭代),然后在其上映射并在每次迭代时返回一个带有所需id的输入副本:
编辑:更新以包含可见的逻辑(在第一篇文章中遗漏)
const-input={id:0,visible:true,width:200,height:200};
常量输出=数组(10).fill(0).map((x,id)=>({…输入,可见:id==0,id}));
console.log(output)
这是我的草稿,但是如果你想得到一个好的答案,在要求我们花时间为你做每件事之前,你还需要向我们展示你尝试了什么以及你遇到了什么困难
const mock = {
id: 0,
visible: true,
width: 200,
height: 200
}
let mockArr = [];
for (i = 0; i <= 10; i++) {
mockArr.push({
...mock,
visible: i === 0,
id: i
})
}
console.log(mockArr)
const mock={
id:0,
可见:对,
宽度:200,
身高:200
}
设mockArr=[];
对于(i=0;i我的建议
let input={id:0,visible:true,width:200,height:200}
让输出=[];
对于(let i=0;iNice,您能发布一些代码吗?我们很乐意提供帮助。要求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作的摘要,以及您解决问题的困难的描述。请阅读和发布。const output=input=>Array.from({length:10},index=>index==0?input:Object.assign({},input,{visible:false,id:index});console.log(output(input));
数组。from({length:10},(x,id)=>({…input,visible:id==0,id}));
是最短的版本,也是最快的改进!