jQuery 객체 평등
두 개의 jQuery 객체가 같은지 어떻게 알 수 있습니까? 특정 jQuery 객체에 대한 배열을 검색하고 싶습니다.
$.inArray(jqobj, my_array);//-1
alert($("#deviceTypeRoot") == $("#deviceTypeRoot"));//False
alert($("#deviceTypeRoot") === $("#deviceTypeRoot"));//False
jQuery 1.6부터 사용할 수 있습니다 .is
. 아래는 1 년 전의 답변입니다 ...
var a = $('#foo');
var b = a;
if (a.is(b)) {
// the same object!
}
두 변수가 실제로 동일한 객체인지 확인하려면 다음과 같이하십시오.
var a = $('#foo');
var b = a;
... 그러면 고유 한 ID를 확인할 수 있습니다. 새 jQuery 객체를 만들 때마다 ID를 얻습니다.
if ($.data(a) == $.data(b)) {
// the same object!
}
간단한 방법으로도 동일한 결과를 얻을 수 있지만 a === b
위의 내용은 적어도 다음 개발자에게 테스트 대상을 정확하게 보여줄 수 있습니다.
어쨌든, 그것은 아마도 당신이 추구하는 것이 아닐 것입니다. 두 개의 다른 jQuery 객체에 동일한 요소 집합이 포함되어 있는지 확인하려면 다음을 사용할 수 있습니다.
$.fn.equals = function(compareTo) {
if (!compareTo || this.length != compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
var a = $('p');
var b = $('p');
if (a.equals(b)) {
// same set
}
여전히 모르는 경우 다음을 수행하여 원본 객체를 다시 가져올 수 있습니다.
alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //True
alert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True
$("#deviceTypeRoot")
또한 선택자가 선택한 객체의 배열을 반환 하기 때문 입니다.
$.fn.equals(...)
솔루션은 아마도 가장 깨끗하고 가장 우아한 하나입니다.
나는 다음과 같이 빠르고 더러운 것을 시도했다.
JSON.stringify(a) == JSON.stringify(b)
아마도 비싸지 만 편안한 것은 암묵적으로 재귀 적이지만 우아한 해결책은 그렇지 않다는 것입니다.
그냥 내 2 센트.
일반적으로 말하자면 $ (foo)와 $ (foo)를 비교하는 것은 좋지 않습니다. 이는 기능적으로 다음 비교와 같습니다.
<html>
<head>
<script language='javascript'>
function foo(bar) {
return ({ "object": bar });
}
$ = foo;
if ( $("a") == $("a") ) {
alert ("JS engine screw-up");
}
else {
alert ("Expected result");
}
</script>
</head>
</html>
물론 "JS 엔진 스크류 업"을 기대하지는 않을 것입니다. jQuery가 무엇을하고 있는지 명확하게하기 위해 "$"를 사용합니다.
$ ( "# foo")를 호출 할 때마다 실제로 새 객체 를 반환하는 jQuery ( "# foo")를 수행 합니다 . 따라서 그것들을 비교하고 동일한 객체를 기대하는 것은 정확하지 않습니다.
However what you CAN do may be is something like:
<html>
<head>
<script language='javascript'>
function foo(bar) {
return ({ "object": bar });
}
$ = foo;
if ( $("a").object == $("a").object ) {
alert ("Yep! Now it works");
}
else {
alert ("This should not happen");
}
</script>
</head>
</html>
So really you should perhaps compare the ID elements of the jQuery objects in your real program so something like
...
$(someIdSelector).attr("id") == $(someOtherIdSelector).attr("id")
is more appropriate.
Use Underscore.js isEqual method http://underscorejs.org/#isEqual
First order your object based on key using this function
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
Then, compare the stringified version of your object, using this funtion
function isEqualObject(a,b){
return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}
Here is an example
Assuming objects keys are ordered differently and are of the same values
var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}
isEqualObject(obj1,obj2);//returns true
If you want to check contents are equal or not then just use JSON.stringify(obj)
Eg - var a ={key:val};
var b ={key:val};
JSON.stringify(a) == JSON.stringify(b) -----> If contents are same you gets true.
참고URL : https://stackoverflow.com/questions/3176962/jquery-object-equality
'Programming' 카테고리의 다른 글
Java 프로그래머가 변수 이름을 "clazz"로 지정하는 이유는 무엇입니까? (0) | 2020.06.18 |
---|---|
Javascript 반복자를 배열로 변환 (0) | 2020.06.18 |
=>, () => 및 Unit =>의 차이점은 무엇입니까? (0) | 2020.06.18 |
Visual Studio :보기 코드를 기본으로 설정 (0) | 2020.06.18 |
jQuery 요소가 DOM에 있는지 어떻게 확인합니까? (0) | 2020.06.18 |