简体   繁体   English

在对象内的javascript中填充数组

[英]Fill an array in javascript inside an object

i'm new to javascript and i have a little issue. 我是javascript新手,但有一个小问题。 I have an array like this: 我有一个像这样的数组:

name = ["Alex","John", "Mark"].

After that, i have and object with an array inside like this: 之后,我有一个对象,里面有一个像这样的数组:

ObjectNames = {
  labels: []
}

I want to fill the labels array with the content of tha name array like this: 我想用tha名称数组的内容填充labels数组,如下所示:

labels = [name[0], name[1], name[2]]

How to do this? 这个怎么做?

What you did in your question already solves your problem, but you can try this: 您在问题中所做的事情已经解决了您的问题,但是您可以尝试以下操作:

ObjectNames = {
    labels: names
}

This will make a copy of names and store it in labels. 这将复制名称并将其存储在标签中。

Let me know if it works 让我知道是否有效

Edit: As Andrew Li pointed out, there's no need to use slice, as JavaScript automatically creates a copy 编辑:正如安德鲁·李(Andrew Li)指出的那样,无需使用切片,因为JavaScript会自动创建一个副本

You could do it like this : 您可以这样做:

 var _name = ["Alex","John", "Mark"]; var ObjectNames = { labels: [] }; _name.forEach(function(e) { ObjectNames.labels.push(e); }); console.log(ObjectNames.labels); 

There are lots of way you can do that 有很多方法可以做到这一点

Try like this 这样尝试

var ObjectNames = {
  labels: [name[0], name[1], name[2]]
}

or 要么

var ObjectNames = {
  labels: name
}

or 要么

var ObjectNames = {
  labels: name.slice()
}

or 要么

ObjectNames = {
  labels: []
}

ObjectNames.labels=name ;

or like this 或像这样

for(var i=0;i<name.length;i++)
  ObjectNames.labels.push(name[i])

or 要么

name.forEach(x=> ObjectNames.labels.push(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM