【问题标题】:How can I check that two array are equal or not? [duplicate]如何检查两个数组是否相等? [复制]
【发布时间】:2017-08-11 15:32:45
【问题描述】:

我正在尝试比较两个数组是否相等。我正在破坏数组a,最后将它们存储到两个不同的数组bc 中。最后,我在控制台中检查数组bc

控制台显示相等的值,但是当我比较两个数组时,我得到的数组不相等。

这是我的代码:

var a = [1,2,3,4,3,2,1];
var b = [];
var c = [];
var t = 0;
var length = a.length;

console.log("is the array length" + length);
if (length %2 !== 0) {
    var mid = parseInt(length/2)-1;
    console.log(a[mid]);
    for(var j=length-1; j>(mid+1); j--) {
        c[t] = a[j];
        t++;
    }
    for(var i=0; i<=mid; i++) {
        b[i] = a[i];
    }
    console.log(c);
    console.log(b);

    if(b == c) { //comparing the array b and c
        console.log("true");
    }
    else {
        console.log("no")
    }
}

这是我的 jsbin 链接:https://jsbin.com/metexuruka/edit

【问题讨论】:

  • 数组永远不会相等。它们存储在不同的内存位置。
  • 所以我不能比较两个数组??

标签: javascript arrays


【解决方案1】:

取决于你对“相等”的定义——如果两个数组在相同的位置包含相同的元素,你可以使用every:

let areEqual = a.length === b.length && a.every((item, index) => b[index] === item);

如果你只想检查它们是否包含相同的元素,你仍然可以使用every,只是没有索引检查:

let areEqual = a.length === b.length && a.every(item => b.indexOf(item) > -1);

【讨论】:

    【解决方案2】:

    首先,拆分数组的代码过于复杂。你可以简单地切片:

     var a= [1,2,3,4,3,2,1],
     mid = Math.floor(a.length/2),
     b = a.slice(0,mid),
     c = a.slice(mid).reverse();
    

    要比较两个数组,您可以创建一个字符串(因为您可以轻松比较字符串):

     if(b.join() === c.join()) alert("equal");
    

    或者你迭代并检查每个:

    if( b.length === c.length 
        && b.every((v,i)=> v === c[i])) alert("equal");
    

    如果你只是想比较 a 是否是一个字谜,它更容易:

    var a= [1,2,3,4,3,2,1];
    
    if( a.every((v,i)=>v===a[a.length-1-i]) ) alert("anagram!");
    

    【讨论】:

    • 我希望数组 C 以相反的方式进行,所以我使用 for 循环以相反的顺序获得它......因为我无法使用 slice 方法做到这一点。
    • @ashish sah,这就是 .reverse() 的好处...
    【解决方案3】:

    它太长了,但你可以用这个:

    <script type="text/javascript">
            /*$(function () {
                $(".nav-item").click(function () {
                    $(".nav-item").each(function () {
                        $(this).find("a").removeClass("active");
                    });
                    $(this).find("a").addClass("active");
                });
            });*/
    
            // Warn if overriding existing method
            if (Array.prototype.equals)
                console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
            // attach the .equals method to Array's prototype to call it on any array
            Array.prototype.equals = function (array) {
                // if the other array is a falsy value, return
                if (!array)
                    return false;
    
                // compare lengths - can save a lot of time 
                if (this.length != array.length)
                    return false;
    
                for (var i = 0, l = this.length; i < l; i++) {
                    // Check if we have nested arrays
                    if (this[i] instanceof Array && array[i] instanceof Array) {
                        // recurse into the nested arrays
                        if (!this[i].equals(array[i]))
                            return false;
                    }
                    else if (this[i] != array[i]) {
                        // Warning - two different object instances will never be equal: {x:20} != {x:20}
                        return false;
                    }
                }
                return true;
            }
            // Hide method from for-in loops
            Object.defineProperty(Array.prototype, "equals", { enumerable: false });
    
            var a = [1, 2, 3, 4, 3, 2, 1];
            var b = []; var c = []; var t = 0;
            var length = a.length;
            alert("is the array length" + length);
            if (length % 2 !== 0) {
                var mid = parseInt(length / 2) - 1;
                alert(a[mid]);
                for (var j = length - 1; j > (mid + 1) ; j--) {
                    c[t] = a[j];
                    t++;
                }
                for (var i = 0; i <= mid; i++) {
                    b[i] = a[i];
                }
                alert(c);
                alert(b);
    
                if (b.equals(c)) { //comparing the array b and c
                    alert("true");
                }
                else
                    alert("no");
            }
        </script>

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 2017-09-09
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多