简体   繁体   English

在数组中搜索并匹配值

[英]Searching in an array and matching the values

I have two fields whose names are: Format field and Extension field.我有两个字段,其名称是:格式字段和扩展字段。

I have to match both the fields like:我必须匹配两个字段,例如:

var format     = $("#someid").val();// Eg value is excel;
var extension  = $("#someid").val();// eg value is xls;
var FormatCheck= {"excel":["xls","xlsx"],"word":["doc","docx"],"html"["htm","html"],"mpp":["mpp"],"pdf":["pdf"],"ppt":["ppt","pptx"]};

Then I have to compare thevalue of Format and Extension fields with the array in FormatCheck .然后我必须将 Format 和 Extension 字段的值与FormatCheck的数组进行FormatCheck

If it matches exactly the array then I have to insert it.如果它与数组完全匹配,那么我必须插入它。

This should work,这应该有效,

var format     = $("#format_id").val();// Eg value is excel;
var extension  = $("#ext_id").val();// eg value is xls;
var FormatCheck= [excel["xls","xlsx"],word["doc","docx"],html["htm","html"],mpp["mpp"],pdf["pdf"],ppt["ppt","pptx"]];   //Double dimensional array,

function validExtension(format, extension, FormatCheck){ 
  for(var i = 0 , len = FormatCheck.length; i < len; i++){
     if($.inArray(FormatCheck[format], extension) == 1) return true; //Check if the format exists.
  }
  return false;
}

validExtension("excel","xls", FormatCheck)   //returns true.

It would be simpler if your FormatCheck was organized differently:如果您的 FormatCheck 以不同的方式组织会更简单:

var FormatCheck = {"xls": "excel", "xlsx": "excel", ... }

Otherwise, you need to scan the whole table to find the extension:否则,您需要扫描整个表以找到扩展名:

var type = null;
$.each(FormatCheck, function(key,val) {
    if ($.inArray(val, extension) >= 0) {
        type = key;
    }
});

you do not need jquery for that.你不需要jquery。 You could try this你可以试试这个

var FormatCheck = "xls,xlsx,doc,docx,html,htm,html,mpp,pdf,ppt,pptx".indexOf($("#someid").val()) > -1;

if(FormatCheck) { /*extension is in range*/}
else { /*it is not*/}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM