comparing two 2d arrays in jquery

北城余情 提交于 2019-12-10 11:12:52

问题


I'm trying to compare two arrays both 2d, I need it only match when they're completely identical. The code I have is too lengthly, as the arrays will potentially be far longer. I tried playing with .each() and for loops but it get's very messy and won't compare every array.

var solution=[
[0,0,0],
[0,0,1],
[0,0,1]];

var value=[
[0,0,0],
[0,0,1],
[0,0,1]];

//compare arrays
    if (solution[0][0]==value[0][0] &&
        solution[0][1]==value[0][1] &&
        solution[0][2]==value[0][2] &&
        solution[1][0]==value[1][0] &&
        solution[1][1]==value[1][1] &&
        solution[1][2]==value[1][2] &&
        solution[2][0]==value[2][0] &&
        solution[2][1]==value[2][1] &&
        solution[2][2]==value[2][2]) { 

        $('h1').show();

    }
    else { $('h1').hide();}

回答1:


simple trick, by making them into strings :)

function equalArray(a, b) {
    return JSON.stringify(a) == JSON.stringify(b);
}



回答2:


You can compare arrays using

 $(solution).compare(value)


来源:https://stackoverflow.com/questions/8775658/comparing-two-2d-arrays-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!