在数组中搜索并匹配值

时间:2013-08-16 07:33:34

标签: jquery arrays

我有两个字段,其名称是:格式字段和扩展字段。

我必须匹配两个字段:

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"]};

然后我必须将Format和Extension字段的值与FormatCheck中的数组进行比较。

如果它与数组完全匹配,那么我必须插入它。

3 个答案:

答案 0 :(得分:0)

我希望这应该有用,

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.

有人在某处错了,请帮我纠正答案。

答案 1 :(得分:0)

如果您的FormatCheck组织方式不同,那会更简单:

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

否则,您需要扫描整个表以查找扩展名:

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

答案 2 :(得分:-1)

你不需要jquery。你可以试试这个

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*/}