将原生 javascript 对象与 jQuery 进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3791516/
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
Comparing native javascript objects with jQuery
提问by Russell
Possible Duplicate:
Object comparison in JavaScript
可能的重复:
JavaScript 中的对象比较
I have two native JavaScript objects:
我有两个原生 JavaScript 对象:
var foo = { hello: 'world', holy: { shit: 'batman' } };
var bar = { ... };
I would like to compare the two (foo == bar).
我想比较两者(foo == bar)。
回答by Joe
This works well, but only in some cases:
这很有效,但仅在某些情况下:
var obj1 = {n1: "v1", n2: "v2"},
obj2 = {n1: "v1", n2: "v2"},
obj3 = {n2: "v2", n1: "v1"},
obj4 = {n2: "v2", n1: "v1", f: function(){}};
// this will work correctly:
JSON.stringify(obj1) == JSON.stringify(obj2); //true
// but this fails :(
JSON.stringify(obj2) == JSON.stringify(obj3); //false
// and this :(
JSON.stringify(obj3) == JSON.stringify(obj4); //true
回答by RMorrisey
jQuery has no built-in utility for comparing objects. It's not really clear from your post what information you want to derive from your two objects. Are you trying to sort them?
jQuery 没有用于比较对象的内置实用程序。从您的帖子中并不清楚您想从两个对象中获取哪些信息。你想对它们进行排序吗?
Depending on what you are trying to do, you may be able to satisfy your use case by using one of jQuery's utility methods, though. See, for example: jQuery.extend, jQuery.each, jQuery.map, and jQuery.merge. jQuery is primarily concerned with manipulating DOM elements; it doesn't have a built-in feature for list sorting (though you may be able to find a plugin).
不过,根据您尝试执行的操作,您可以通过使用 jQuery 的实用程序方法之一来满足您的用例。参见,例如:jQuery.extend,jQuery.each,jQuery.map,和jQuery.merge。jQuery 主要关注操作 DOM 元素;它没有用于列表排序的内置功能(尽管您可以找到一个插件)。
Check out the jQuery utilities documentation:
查看 jQuery 实用程序文档:
http://api.jquery.com/category/utilities/
http://api.jquery.com/category/utilities/
Also, check out array.sort(), which apparently is built into javascript:
另外,请查看array.sort(),这显然是内置在 javascript 中的:

