js数组对象判断

var a1 = [

{text:"你"},
{text:"好"}

]
var b1 = [

{text:"你"},
{text:"好"}

]

var a2 = [

{text:"你"},
{text:"好"}

]
var b2 = [

{text:"你"},
{text:"们"}

]
写个方法判断上面啊a跟b 里面text属性的值是否相等 要一一对应 你===你 好===好

比如方法是 fn(a1,b1) //true

       fn(a2,b2)    //false

阅读 2.3k
3 个回答
var a1 = [
        {text:"你"},
        {text:"好"}
    ];
    var b1 = [
        {text:"你"},
        {text:"好"}
    ];
    var a2 = [
        {text:"你"},
        {text:"好"}
    ];
    var b2 = [
        {text:"你"},
        {text:"们"}
    ];
    function fn(a,b){
        return a.every(function(item,index){
            return item.text == b[index].text;
        })
    }
    console.log(fn(a1,b1),fn(a2,b2));
function fn(a, b) => {
    let mapA = {};
    let mapB = {};
    a.forEach(item => {
        if(mapA[item.text]) {
            mapA[item.text] += 1;
        } else {
            mapA[item.text] = 1;
        }
    });
    b.forEach(item => {
        if(mapB[item.text]) {
            mapB[item.text] += 1;
        } else {
            mapB[item.text] = 1;
        }
    });

    return Object.keys(mapA).every(key => {
        return (mapB[key] && mapA[key] == mapB[key]);
    })
}
function fn(a,b){
    a = a.length==0?"":a.map(i=>i.text);
    b = b.length==0?"":b.map(i=>i.text);
    a.sort();b.sort;
    return a.join("") === b.join("")
}
fn([{text:"你"},{text:"好"},{text:"啊"}],[{text:"你"},{text:"啊"},{text:"好"}]);//true
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题