Javascript 向现有对象添加新元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11057802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add new element to an existing object
提问by Mina Gabriel
I was looking for a way to add new elements to an an existing object like what push does with arrays
我正在寻找一种向现有对象添加新元素的方法,就像 push 对数组所做的那样
I have tried this and it didn't work :
我试过这个,但没有用:
var myFunction = {
Author: 'my name ',
date: '15-12-2012',
doSomething: function(){
alert("helloworld")
}
};
myFunction.push({
bookName:'mybook',
bookdesc: 'new'
});
console.log(myFunction);
回答by Danilo Valente
Use this:
用这个:
myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';
Or, if you are using jQuery:
或者,如果您使用的是 jQuery:
$(myFunction).extend({
bookName:'mybook',
bookdesc: 'new'
});
The push
method is wrong because it belongs to the Array.prototype
object.
该push
方法是错误的,因为它属于Array.prototype
对象。
To create a named object, try this:
要创建命名对象,请尝试以下操作:
var myObj = function(){
this.property = 'foo';
this.bar = function(){
}
}
myObj.prototype.objProp = true;
var newObj = new myObj();
回答by sachleen
Just do myFunction.foo = "bar"
and it will add it. myFunction
is the name of the object in this case.
只要这样做myFunction.foo = "bar"
,它就会添加它。myFunction
在这种情况下是对象的名称。
回答by paraS elixiR
jQuery syntax mentioned above by Danilo Valente is not working. It should be as following-
Danilo Valente 上面提到的 jQuery 语法不起作用。应该是这样的——
$.extend(myFunction,{
bookName:'mybook',
bookdesc: 'new'
});
回答by jamesmillerio
You are looking for the jQuery extend method. This will allow you to add other members to your already created JS object.
您正在寻找jQuery 扩展方法。这将允许您向已创建的 JS 对象添加其他成员。
回答by Scott
You could store your JSON inside of an array and then insert the JSON data into the array with push
您可以将 JSON 存储在一个数组中,然后将 JSON 数据插入到数组中 push
Check this out https://jsfiddle.net/cx2rk40e/2/
看看这个https://jsfiddle.net/cx2rk40e/2/
$(document).ready(function(){
// using jQuery just to load function but will work without library.
$( "button" ).on( "click", go );
// Array of JSON we will append too.
var jsonTest = [{
"colour": "blue",
"link": "http1"
}]
// Appends JSON to array with push. Then displays the data in alert.
function go() {
jsonTest.push({"colour":"red", "link":"http2"});
alert(JSON.stringify(jsonTest));
}
});
Result of JSON.stringify(jsonTest)
的结果 JSON.stringify(jsonTest)
[{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]
This answer maybe useful to users who wish to emulate a similar result.
这个答案可能对希望模拟类似结果的用户有用。