[英]How to append an element into a existing array in javascript/jquery
I have an array in javascript 我在javascript中有一个数组
var myArr = {
'textId':'123',
'type':'animal',
'content':'hi dog',
'expires':'27/10/2012'
};
$.each(myArr, function(myArrArrKey, myArrArrValue){
console.log( myArrArrValue );
});
The above console prints following values 上面的控制台打印以下值
123
app
hi app
27/10/2012
Now i am want to append an element to the existing array, i am trying to do like the below one 现在我想将一个元素附加到现有数组,我想尝试像下面这样做
myArrValue.push({'status':'active'});
The above push throws following error 以上推送抛出以下错误
TypeError: Object #<Object> has no method 'push'
Kindly help me how to append to that existing array element. 请帮助我如何附加到现有的数组元素。
I want to print the array like 我想打印数组
123
app
hi app
27/10/2012
active
Just do this. 就这样做吧。
myArr.status = 'active'
or 要么
myArr["status"] = 'active'
Your myArr
is an Object
not an Array
.. 你的
myArr
是一个Object
而不是一个Array
..
push
function is available to an Array
variable. push
函数可用于Array
变量。
this isn't an array, it's an object! 这不是一个数组,它是一个对象!
var myArr = {
'textId':'123',
'type':'animal',
'content':'hi dog',
'expires':'27/10/2012'
};
this isn't necessary with jQuery 这对jQuery来说不是必需的
$.each(myArr, function(myArrArrKey, myArrArrValue){
console.log( myArrArrValue );
});
easier would be 更容易
for ( var k in myArr ) {
console.log( myArr[ k ];
}
to add new entries to your "array" 向“数组”添加新条目
myArr[ 'foo' ] = 'bar'; // this is array notation
or 要么
myArr.foo = 'bar'; // this is object notation
to remove entries from your "array" 从“阵列”中删除条目
delete myArr[ 'foo' ];
or 要么
delete myArr.foo;
FYI: myArrValue.push({'status':'active'});
仅供参考:
myArrValue.push({'status':'active'});
wont work. 不会工作。 myArrValue isn't the "array" itself and also not an array having the method
push
. myArrValue本身不是“数组”,也不是具有方法
push
的数组。 If it would be an array the result would be, that your latest entry is the whole an object {'status':'active'}
如果它是一个数组结果,那么你的最新条目就是整个对象
{'status':'active'}
The answer is in the error... you have an object, not an array. 答案是在错误中...你有一个对象,而不是一个数组。 Use object notation
使用对象表示法
myArr.status='active'
Simply use: 只需使用:
myArrValue.status = 'active';
but be aware that what you are using is an object , not an array. 但请注意,您使用的是对象 ,而不是数组。 Another way to add properties to an object is:
向对象添加属性的另一种方法是:
object[key] = value;
这个json对象不是数组推送用于json的数组
myObj.NewProp = 123;
Just for the kicks of it.. 只为了它的踢..
function push( obj ) {
var prop;
for ( prop in obj ) {
this[prop] = obj[prop];
}
return this;
}
Your object, remember to assing the push method. 你的对象,记得要帮助推送方法。
var obj = {
a: "a",
b: "b",
push: push
};
And the push: 推动:
obj.push({
c: "c",
d: "d"
});
myArr["status"] = 'active';
要么
myArr.status ='active';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.