比较javascript数组 [英] comparing javascript arrays

查看:80
本文介绍了比较javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个与javascript字符串数组进行比较的函数,并将不匹配的值保存到新数组中.目前,即时通讯使用了嵌套的jquery foreach.但是我认为有比这更好的方法了吗?

I would like a function that compares to arrays of javascript strings, and saving the values that didnt match in to a new array. At the moment im using a nested jquery foreach. But i think there are better ways than this?

$.each(imagesInUploadsFolder, function(i, outervalue){
            $.each(imagesInDatabaseTable, function(i, innervalue){

                if(outervalue == innervalue){
                    //match in both arrays...
                } 

            });
        });

推荐答案

这是使用JSON对象而不使用jQuery的方法,尽管$.inArray()应该可以正常工作:

Here's a way using a JSON object and no jQuery, although the $.inArray() should work fine:

var imagesInUploadsFolder = [
    '/path/to/img1.png',
    '/path/to/img2.png',
    '/path/to/img3.png'
];
var imagesInDatabaseTable = [
    '/path/to/img1.jpg',
    '/path/to/img2.png',
    '/path/to/img4.png'
];

var database_json = JSON.stringify(imagesInDatabaseTable);

for (var i = 0; i < imagesInUploadsFolder.length; i++) {
    console.log(imagesInUploadsFolder[i] + ' in ' + database_json);
    if (database_json.indexOf(imagesInUploadsFolder[i]) > -1) {
        console.log('In database: ' + imagesInUploadsFolder[i]);
    } else {
        console.log('Not in database: ' + imagesInUploadsFolder[i]);
    }
}

http://jsfiddle.net/7nJPW/1/

编辑

实际上,不需要JSON方法(?):

Actually, the JSON method isn't needed (?):

for (var i = 0; i < imagesInUploadsFolder.length; i++) {
    console.log(imagesInUploadsFolder[i] + ' in ' + imagesInDatabaseTable);
    if (imagesInDatabaseTable.indexOf(imagesInUploadsFolder[i]) > -1) {
        console.log('In database: ' + imagesInUploadsFolder[i]);
    } else {
        console.log('Not in database: ' + imagesInUploadsFolder[i]);
    }
}

http://jsfiddle.net/7nJPW/2/

这篇关于比较javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆