javascript 如何将项目添加到嵌套数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8851798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:46:33  来源:igfitidea点击:

How do I add items to a nested Array?

javascriptarrays

提问by amlane86

Say I have an array such as this in Javascript:

假设我在 Javascript 中有一个这样的数组:

var cars = { vendor: [ { type: [ 'camry', 'etc' ] } ] } 

In Javascript what command can I use to add an item to type... For example if I wanted to have a text box that a user can place text into and then hit a button that will add the item into the array. The item that would be added would need to be placed in with the same items as "camry" and "etc". Thanks!

在Javascript中,我可以使用什么命令来添加要键入的项目...例如,如果我想要一个文本框,用户可以将文本放入其中,然后点击一个按钮将项目添加到数组中。要添加的项目需要与“camry”和“etc”相同的项目一起放置。谢谢!

回答by Hyman

Try something like

尝试类似

cars.vendor[0].type.push("foo");

Where "foo" is your data to add.

其中“foo”是您要添加的数据。

回答by Matt

You can add items to the array using the push()method to add to the end, or unshift()to add to the front.

您可以使用push()添加到末尾或unshift()添加到前面的方法向数组添加项。

var newValue = 1234;

cars.vendor[0].type.push(newValue);

The event handler could then be bound using something similar to this;

然后可以使用类似于此的方法绑定事件处理程序;

$("yourSelector").on("click", function(){
    var value = $("input").val();

    cars.vendor[0].type.push(value);
});

Pleasebear in mind that what you have is not JSON at all. It's a nested structure of JavaScript Objects and Arrays, declared using literal syntax. See Javascript object Vs JSONfor more info.

记住,您所拥有的根本不是 JSON。它是 JavaScript 对象和数组的嵌套结构,使用文字语法声明。有关更多信息,请参阅Javascript 对象与 JSON

回答by Umesh Patil

Sample Test example for this problem as below:

此问题的示例测试示例如下:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
    var cars = {
        "vendor": [
            {
                "type": [
                    "camry",
                    "maruti",
                    "bmw"
                ]
            }
        ]
    };
    $("#add").click(function(){
        var types=cars["vendor"][0]["type"];
        types.push($("#json").val());
        $("#types").html(types.toString());
    });
});
</script>
</head>
<body>
<input type="text" id="json" name="json"/>
<input type="button" id="add" name="add" value="ADD"/>
<div id="types" style="margin:10px;border:1px dotted green;width:400px;"></div>
</body>
</html>

回答by Amulya

You can try something like given below

你可以尝试下面给出的东西

var cars = { vendor: [ { type: [ 'camry', 'etc' ] } ] } ;
cars.vendor[0].type[2]="abc";