简体   繁体   English

数组不是作为新索引推送,而是作为新数组推送

[英]Array not being pushed as a new index, but as a new array

My object contains the following format:我的对象包含以下格式:

[
    { },
    { }
]

But the way my code is written, it adds it in as,但是我的代码的编写方式,将其添加为,

[
    [
        { }
    ],
    [
        { }
    ]
]

Not sure what's going on, here is my code:不知道发生了什么,这是我的代码:

var commentArray = [];

commentArray.push({
    'text': comment,
    'user': vm.user
});

reference.reference.comments.push(commentArray);

Something like this works:像这样的工作:

reference.reference.comments.push({
    'text': comment,
    'user': vm.user
});

But I want to push commentArray ?但我想推送commentArray

Let's see if I can make it clear to you:看我能不能给你说清楚:

var commentArray = []; 
// here you are creating an empty array called commentArray 

commentArray.push({
    'text': comment,
    'user': vm.user
}); 
// Here you define an object, with 2 properties (text and user) 
// and push it to commentArray you created so 
// commentArray = [{'text': comment, 'user': vm.user}];

reference.reference.comments.push(commentArray);
/// here you push an array (commentArray) into another array (comments)
// so reference.reference.comments will be [[{'text': comment, 'user': vm.user}]];

I'll do a working example in a moment.稍后我将做一个工作示例。

 var comments = []; var commentArray = []; commentArray.push({ 'text': 'comment', 'user': 'someuser' }); console.log('comments:', comments); console.log('commentArray:', commentArray); comments.push(commentArray); console.log('comments:', comments); console.log('commentArray:', commentArray);

So you shouldn't create an intermediary array.所以你不应该创建一个中间数组。 You should create only the object.您应该只创建对象。 Like this:像这样:

var comment = {
    'text': comment,
    'user': vm.user
};

reference.reference.comments.push(comment);

or more directly like this:或更直接地像这样:

reference.reference.comments.push({
    'text': comment,
    'user': vm.user
});

Try this, you want to push a single comment into your comments array, not an array into an array.试试这个,您想将单个评论推送到您的评论数组中,而不是将数组放入数组中。

var comment = {
    'text': comment,
    'user': vm.user
};

reference.reference.comments.push(comment);

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

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