无法动态地在JSON对象中添加值

时间:2017-01-27 01:43:59

标签: javascript jquery json

我正在尝试将对象添加到JSON对象中,就像

一样
 var books = [{
                "no" : 1,
                "bookType":"fiction",
                "bookPrice": 60

            },{
                "no" : 2,
                "bookType":"fun",
                "bookPrice": 40

            }
            ....
  ]

但是输出是如此不同!你能告诉我怎么解决这个问题吗?

 $(document).ready(function() {
         var books = [];
            $('.addItem').on('click', function() {
            var type = $(this).data('type');
            var price = $(this).data('price');
            books.push('{',type, '"',price,'"}'),
            console.log(books);
            });

        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="addItem" data-type="fiction" data-price="50">Add Book</button>
<button class="addItem" data-type="fun" data-price="40">Add Book</button>

1 个答案:

答案 0 :(得分:3)

这是因为您插入了字符串而不是对象。您不需要对对象进行字符串化以插入数组。数组可以容纳对象。

&#13;
&#13;
$(document).ready(function() {
         var books = [];
            $('.addItem').on('click', function() {
            var type = $(this).data('type');
            var price = $(this).data('price');
            books.push({
              "no":books.length,
              "bookType":type,
              "bookPrice":price
             });
            console.log(books);
            });

        });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="addItem" data-type="fiction" data-price="50">Add Book</button>
<button class="addItem" data-type="fun" data-price="40">Add Book</button>
&#13;
&#13;
&#13;