[英]Comparing arrays in javascript error
我试图比较2 json值列表。 如果比较为真,则不显示该显示,而仅显示该语句为假的值。
这是代码:
var files= '{"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com\/files\/doc2.pdf"}]}';
var result = '[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},';
for (var i = 0; i < files.length; i++) {
var file = files[i];
for(var j=0;j<arrayResults.length;j++){
if (files[i]==arrayResults[j].json.name){
alert("Matching found");
//full_list = full_list + arrayResults[j].json.name + " " + arrayResults[j]._id + " " + arrayResults[j].json.title + " " + arrayResults[j].json.path + '<br />';
}else {
alert("no similar files");
str += '<br /><div class="fileSection">' + '<br/>' + '<input class="fileName" type="hidden" value="'+ file.name + '" />' + file.name + '<br/>' + '<input class="fileTitle" type="hidden" value="'+ file.title +'" />' + file.title + '<br/>' + '<input class="filePath" type="hidden" value="'+ file.path +'" />' + '<button onclick="add(this)">Add</button> '+ '</div><br/>' ;
}
}
输出结果应仅为doc2.pdf的json列表。 相反,它只是显示所有列表。
如果能得到帮助,我将不胜感激。
如果要比较javascript中的某些内容,则最好使用===
而不进行类型转换,而不要使用==
。
参见此处: 平等比较和相同性
有几件事需要纠正。 主要是可以使用JSON.parse()
提取数据:
var files= '{"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\\/files\\/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com\\/files\\/doc2.pdf"}]}'; var result = '[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\\/files\\/doc1.pdf"}]'; // you need to convert the above strings to arrays: files = JSON.parse(files).files; // You need the files property arrayResults = JSON.parse(result); for (var i = 0; i < files.length; i++) { var file = files[i]; for(var j=0;j<arrayResults.length;j++){ // note the name property on the files[i] object: if (files[i].name===arrayResults[j].name){ alert("Matching found for " + files[i].name); }else { alert("no similar files for " + files[i].name); } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.