如何使用 JavaScript 或 jQuery 清除 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17646974/
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
How to clear JSON object using JavaScript or jQuery
提问by PSR
I have a JSON object as follows. After sending ajax call I want to clear this. How I can do?
我有一个 JSON 对象,如下所示。发送 ajax 调用后,我想清除它。我能怎么办?
var cfamFwdDtls = {
cndtwizid: [],
clientIdsInstnIds: [],
positioncd: '',
positionCnt: '',
rcrtrInstnId: '',
positionLocation: {
cntryIdFrCndt: '',
stateIdFrCndt: '',
zipIdFrCndt: '',
cityIdFrCndt: ''
},
searchPstnSkill: []
};
回答by Shawn31313
Just reset the variable back to {}
;
只需将变量重置回{}
;
cfamFwdDtls = {};
// or
cfamFwdDtls = new Object;
And this is the moment when you start thinking: "Whoooa, I can't believe it's that easy."
这就是你开始思考的时刻:“哇哦,我简直不敢相信这么容易。”
In special cases:
特殊情况下:
You could take the "long" way:
你可以走“长”路:
for (var key in cfamFwdDtls) {
delete cfamFwdDtls[key];
}
For your purposes, this is not extremely practical, but in case you would like to be a little more selective, looping is the way to go.
就您的目的而言,这不是非常实用,但如果您想更具选择性,循环是可行的方法。
回答by Nathan
for (var entry in cfamFwdDtls) delete cfamFwdDtls[entry];
for (var entry in cfamFwdDtls) delete cfamFwdDtls[entry];
If you simply reassign to {}
, you'll get in trouble if there are multiple references to your object. Also may face garbage collection issues.
如果您简单地重新分配给{}
,那么如果您的对象有多个引用,您就会遇到麻烦。也可能面临垃圾收集问题。