2

我在javascript中有一个数组

var myArr = {
    'textId':'123', 
    'type':'animal', 
    'content':'hi dog', 
    'expires':'27/10/2012' 
};

$.each(myArr, function(myArrArrKey, myArrArrValue){
    console.log( myArrArrValue );
});

上面的控制台打印以下值

123
app
hi app
27/10/2012

现在我想将一个元素附加到现有数组中,我正在尝试像下面这样

myArrValue.push({'status':'active'});

上述推送引发以下错误

TypeError: Object #<Object> has no method 'push'

请帮助我如何附加到现有的数组元素。
我想像这样打印数组

123
app
hi app
27/10/2012
active
4

7 回答 7

4

就这样做吧。

myArr.status = 'active'

或者

myArr["status"] = 'active'

myArrObject不是一个Array..

push函数可用于Array变量。

于 2012-10-27T11:17:29.547 回答
3

这不是一个数组,它是一个对象!

var myArr = {
    'textId':'123', 
    'type':'animal', 
    'content':'hi dog', 
    'expires':'27/10/2012' 
};

这对 jQuery 来说不是必需的

$.each(myArr, function(myArrArrKey, myArrArrValue){
    console.log( myArrArrValue );
});


会更容易

for ( var k in myArr ) {
    console.log( myArr[ k ];
}


将新条目添加到您的“数组”

myArr[ 'foo' ] = 'bar';  // this is array notation

或者

myArr.foo = 'bar';  // this is object notation


从“数组”中删除条目

delete myArr[ 'foo' ];

或者

delete myArr.foo;


仅供参考: myArrValue.push({'status':'active'});不会工作。myArrValue 不是“数组”本身,也不是具有方法的数组push。如果它是一个数组,结果将是,您的最新条目是整个对象{'status':'active'}

于 2012-10-27T11:25:02.190 回答
2

答案就在错误中……你有一个对象,而不是一个数组。使用对象符号

myArr.status='active'
于 2012-10-27T11:18:26.687 回答
2

只需使用:

myArrValue.status = 'active';

但请注意,您使用的是对象,而不是数组。向对象添加属性的另一种方法是:

object[key] = value;
于 2012-10-27T11:19:07.237 回答
2

这是一个 json 对象而不是数组 push 会为你做的 json 数组

myObj.NewProp = 123;
于 2012-10-27T11:19:17.713 回答
2

只是为了它的踢..

function push( obj ) {
    var prop;
    for ( prop in obj ) {
        this[prop] = obj[prop];
    }
    return this;
}

你的对象,记得给 push 方法赋值。

var obj = {
    a: "a",
    b: "b",
    push: push
};

和推动:

obj.push({
    c: "c",
    d: "d"
});
于 2012-10-27T11:22:59.817 回答
1
myArr["status"] = 'active';

或者

myArr.status ='active';
于 2012-10-27T11:21:11.317 回答