简体   繁体   English

在javascript数组中寻找价值

[英]Finding value within javascript array

I'm trying to set up an IF statement if a value is contained within an array. 我试图建立一个IF语句,如果值包含在数组中。

I've found some code which claimed to work but it doesn't seem to be. 我找到了一些声称可以正常工作的代码,但事实并非如此。

var myAsi = ['01','02','24OR01','30De01','9thC01','A.Hu01','A01','AACAMSTE','ABBo01','ABBo02','ABC-01','ACCE01','Acce02','AceR01','h+dm01','Merr02','Ofak01','Wage01','Youn01'];

Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}

var resultHtml = '';
resultHtml+='<table style ="width: 400px">';
resultHtml+='<tr colspan="2">';
resultHtml+='<td colspan="2">';
resultHtml+='<b><font color = "Red">(Client Code)</font><br><font color = "green">(Company Name)</font></b>';
resultHtml+='</td>';
resultHtml+='</tr>';

$.each(data, function(i,item){
  resultHtml+='<div class="result">';
  resultHtml+='<tr>';
  if (notFound=myAsi.find("'"+item.code+"'") == false) {
    resultHtml+='<td>';
  }
  else {
    resultHtml+='<td bgcolor=#D8D8D8>';
  }
  resultHtml+='<font color = "red">'+item.code+'</font><br>';
  resultHtml+='<font color = "green">'+item.content+'</font></td>';
  resultHtml+='<td style ="width: 80px"><a href="delete.php?UserID=<?php echo $userID ?>&AddCode='+item.code+'">Remove</a> - ';
  resultHtml+='<a href="insert.php?UserID=<?php echo $userID ?>&AddCode='+item.code+'">Add</a>';
  resultHtml+='</td>';
  resultHtml+='</tr>';
  resultHtml+='</div>';
  });
resultHtml+='</table>';

The item.code cycles through and I need an IF statement to tell me if it appears within the array. item.code循环遍历,我需要一条IF语句来告诉我它是否出现在数组中。

Any help would be great. 任何帮助都会很棒。

Try removing the apostrophes from your find() call. 尝试从find()调用中删除撇号。 eg 例如

notFound=myAsi.find(item.code)

Though actually, for your purposes see this example which uses this function.... 尽管实际上,出于您的目的,请参见使用此功能的示例。

Array.prototype.find = function(searchStr) {
       for (var i=0; i<this.length; i++) {
           if (this[i]==searchStr) return true;
       };
     return false;    
    };

And as an aside - Be very careful about using var before using a variable - otherwise you create a global variable (which you probably don't want). 顺便说一句-在使用变量之前要非常小心地使用var否则,您将创建一个全局变量(您可能不希望这样做)。 ie the line in your original function.... 即您原始功能中的线。

for (i=0; i<this.length; i++)

i is now global... i现在是全球性的...

If you only want to find if an item is in an array you could use a simpler function than that. 如果只想查找某项是否在数组中,则可以使用比该函数更简单的函数。 For eg. 例如。 the jQuery implementation: jQuery实现:

// returns index of the element or -1 if element not present
function( elem, array ) {
    if ( array.indexOf ) {
        return array.indexOf( elem );
    }
    for ( var i = 0, length = array.length; i < length; i++ ) {
        if ( array[ i ] === elem ) {
            return i;
        }
    }
    return -1;
},

This uses the native browser implementation of indexOf if available (all browsers except IE I think), otherwise a manual loop. 这将使用indexOf的本机浏览器实现(如果可用)(我认为除IE之外的所有浏览器),否则使用手动循环。

Array.prototype.contains = function(value, matcher) {
    if (!matcher || typeof matcher !== 'function') {
        matcher = function(item) {
            return item == value;
        }
    }
    for (var i = 0, len = this.length; i < len; i++) {
        if (matcher(this[i])) {
            return true;
        }
    }
    return false;
};

This returns true for elements in the array that statisfy the conditions defined in matcher. 对于对匹配器中定义的条件进行统计的数组中的元素,此方法返回true。 Implement like this: 像这样实现:

var arr = ['abc', 'def', 'ghi'];   // the array
var valueToFind= 'xyz';  // a value to find in the array

// a function that compares an array item to match
var matcher = function(item) {
    return item === matchThis;
};

// is the value found?
if (arr.contains(valueToFind, matcher)) {
    // item found 
} else {
    // item not found 
}

UPDATES: Changed the contains method to take a value and an optional matcher function. 更新:更改了contains方法以采用一个值和一个可选的matcher函数。 If no matcher is included, it will do a simple equality check. 如果不包含匹配器,它将进行简单的相等性检查。

Test this on jsFiddle.net: http://jsfiddle.net/silkster/wgkru/3/ 在jsFiddle.net上进行测试: http : //jsfiddle.net/silkster/wgkru/3/

You could just use the builtin function 您可以只使用内置功能

['a','b','c'].indexOf('d') == -1

This behavior was mandated in the javascript specification from over 6 years ago. 此行为是6年前的javascript规范中规定的。 Though I gave up on Internet Explorer for these reasons at around IE8, because of this incredibly poor support for standards. 尽管由于这些原因我在IE8左右放弃了Internet Explorer,但由于对标准的支持如此之差。 If you care about supporting very old browsers, you can use http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/ to tack on your own custom Array.indexOf 如果您想支持非常老的浏览器,则可以使用http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/来添加自己的自定义Array.indexOf

I don't recall IE9 supporting [].indexOf, but Microsoft claims it does: http://msdn.microsoft.com/en-us/library/ff679977(v=VS.94).aspx 我不记得支持[] .indexOf的IE9,但Microsoft声称支持:[ http://msdn.microsoft.com/zh-cn/library/ff679977( v = VS.94) .aspx

The standard way to determine the index of the first occurence of a given value in an array is the indexOf method of Array objects. 确定数组中给定值首次出现的索引的标准方法是Array对象的indexOf方法。

This code checks if it this method is supported, and implements it if not, so that it is available on any Array object: 此代码检查是否支持此方法,如果不支持,则实现此方法,以便在任何Array对象上可用:


if(Array.prototype.indexOf==null)
Array.prototype.indexOf = function(x){
    for(var i=0, n=this.length; i<n; i++)if(this[i]===x)return i;
    return -1;
};

Now myArray.indexOf(myValue) returns the first index of myValue in myArray , or -1 if not found. 现在, myArray.indexOf(myValue)返回myArraymyValue的第一个索引;如果未找到,则返回-1

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

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