【问题标题】:Add element to array like json像json一样将元素添加到数组中
【发布时间】:2015-06-12 16:18:39
【问题描述】:

我在 data.push 上收到以下错误。为什么?

Uncaught TypeError: undefined is not a function

在 javascript 中执行此操作时

var data = ({"name": "button", "value": "delete"});
data.push({"id": 456});

console.log(data);

$.ajax({
    type: ...
    url: ...
    data: data,
    dataType: "json"
}).done(function(data) {
    ...
}).fail(function(data) {
    ...
});

【问题讨论】:

  • data[key]=value 允许您为对象指定键+值,而 push() 仅为数组指定值。

标签: javascript


【解决方案1】:

push 是数组的方法,而不是对象

【讨论】:

    【解决方案2】:

    试试这个。您的数据是一个对象,而不是一个数组:

    var data = {"name": "button", "value": "delete"};
    data.id = 456;
    console.log(data);
    

    http://jsfiddle.net/orf40c66/

    有些相关:How to set a Javascript object values dynamically?

    【讨论】:

      【解决方案3】:

      其实data不是一个数组,而是一个对象。数组必须在方括号内声明。

      var data = [{"name": "button", "value": "delete"}];
      console.log(data);

      【讨论】:

        猜你喜欢
        • 2017-09-26
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多