How to test if two objects are the same with JavaScript?

前端 未结 5 2017
慢半拍i
慢半拍i 2021-02-15 17:35

I need a function:

function isSame(a, b){
} 

In which, if a and b are the same, it returns true.
, I tried return a === b, b

5条回答
  •  难免孤独
    2021-02-15 18:09

    Here is something that can work:

    function isSame(obj1, obj2, prefer){
    // Optional parameter prefer allows to only check for object keys and not both keys and values of an object
    var obj_prefer = prefer || "both"; 
    function checkArray(arr1, arr2){
        for(var i = 0, j = obj1.length; i

    Since it converts Functions into Strings to compare them, check out for spaces as that can break things:

    var func1 = function(){},
        func2 = function(){ }; // function with extra space
    isSame(func1, func2); // false
    

    You can check out http://jsfiddle.net/webholik/dwaLN/4/ to try it yourself.

提交回复
热议问题