简体   繁体   English

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

[英]How do I add items to a nested Array?

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. 在Javascript中我可以使用什么命令来添加要键入的项...例如,如果我想要一个文本框,用户可以将文本放入,然后点击一个按钮,将该项添加到数组中。 The item that would be added would need to be placed in with the same items as "camry" and "etc". 要添加的项目需要与“camry”和“etc”相同的项目放置。 Thanks! 谢谢!

Try something like 尝试类似的东西

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

Where "foo" is your data to add. “foo”是您要添加的数据。

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);
});

Please bear in mind that what you have is not JSON at all. 记住,你所拥有的不是JSON。 It's a nested structure of JavaScript Objects and Arrays, declared using literal syntax. 它是JavaScript对象和数组的嵌套结构,使用文字语法声明。 See Javascript object Vs JSON for more info. 有关详细信息,请参阅Javascript对象Vs JSON

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>

You can try something like given below 你可以试试下面给出的东西

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

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

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