Array.push 无法在使用 Node js / javascript 的 forEach 循环中工作
您好,我是 Node js 新手,我正在尝试从对象创建数组
data.forEach((title) => {
let array = [];
for (var i = 0; i <= data.length; i++) {
array.push(title.title.charAt(0).toUpperCase() + title.title.slice(1))
}
console.log(array);
//access.forEach((conf)=>{
// conf.title
// array
//})
})
<script>
let data = [{
title: "user",
fields: "required",
access: "done"
},
{
title: "root",
fields: "default",
access: "done"
},
{
title: "super Admin",
fields: "allready access",
access: "defualt"
},
{
title: "user1",
fields: "required",
access: "done"
},
{
title: "test user",
fields: "required",
access: "done"
},
]
</script>
因为我想要一个包含所有标题的数组,所以我可以在 access.forEach 方法中使用该数组字段,但得到的是标题,但不是在同一个数组中,而是作为不同的输出
预期输出
array = [User,Root,Super Admin,User1,Test user]
Hi I am new to node js and I am trying to make an array from an object
data.forEach((title) => {
let array = [];
for (var i = 0; i <= data.length; i++) {
array.push(title.title.charAt(0).toUpperCase() + title.title.slice(1))
}
console.log(array);
//access.forEach((conf)=>{
// conf.title
// array
//})
})
<script>
let data = [{
title: "user",
fields: "required",
access: "done"
},
{
title: "root",
fields: "default",
access: "done"
},
{
title: "super Admin",
fields: "allready access",
access: "defualt"
},
{
title: "user1",
fields: "required",
access: "done"
},
{
title: "test user",
fields: "required",
access: "done"
},
]
</script>
As I want an array which contain all the title in it so I can use that array field inside the access.forEach method but what am getting is title but not in same array but as a different output
expected output
array = [User,Root,Super Admin,User1,Test user]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过使用简单的 Array.map 来实现此目的()。
工作演示:
You can achieve this by using simple Array.map().
Working Demo :
传入
forEach
的箭头函数会针对data
数组中的每个项目执行,以便您创建一个新数组let array=[]
for你原来的每一件物品。您要么想在函数外部声明数组:或者更好地使用
map
两种情况下的输出均为:
[“用户”、“Root”、“超级管理员”、“User1”、“测试用户”]
An arrow function you pass into
forEach
is executed for every item in thedata
array so that you create a new arraylet array=[]
for every item of your original one. You either want to declare the array outside of the function:or even better use
map
An output in both cases will be:
["User", "Root", "Super Admin", "User1", "Test user"]