[英]How to append an element into a existing array in javascript/jquery
我在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
就這樣做吧。
myArr.status = 'active'
要么
myArr["status"] = 'active'
你的myArr
是一個Object
而不是一個Array
..
push
函數可用於Array
變量。
這不是一個數組,它是一個對象!
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'}
答案是在錯誤中...你有一個對象,而不是一個數組。 使用對象表示法
myArr.status='active'
只需使用:
myArrValue.status = 'active';
但請注意,您使用的是對象 ,而不是數組。 向對象添加屬性的另一種方法是:
object[key] = value;
這個json對象不是數組推送用於json的數組
myObj.NewProp = 123;
只為了它的踢..
function push( obj ) {
var prop;
for ( prop in obj ) {
this[prop] = obj[prop];
}
return this;
}
你的對象,記得要幫助推送方法。
var obj = {
a: "a",
b: "b",
push: push
};
推動:
obj.push({
c: "c",
d: "d"
});
myArr["status"] = 'active';
要么
myArr.status ='active';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.