1389

値が配列に存在するかどうかを判断する必要があります。

私は次の機能を使用しています:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

上記の関数は常に false を返します。

配列値と関数呼び出しは次のとおりです。

arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
4

18 に答える 18

1018

jQueryには、このためのユーティリティ関数があります。

$.inArray(value, array)

valueinのインデックスを返しますarray。を含まない-1場合に返します。arrayvalue

配列に JavaScript のオブジェクトが含まれているかどうかを確認するにはどうすればよいですか?も参照してください。

于 2009-09-24T19:34:44.110 に答える
1015
var contains = function(needle) {
    // Per spec, the way to identify NaN is that it is not equal to itself
    var findNaN = needle !== needle;
    var indexOf;

    if(!findNaN && typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1, index = -1;

            for(i = 0; i < this.length; i++) {
                var item = this[i];

                if((findNaN && item !== item) || item === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle) > -1;
};

次のように使用できます。

var myArray = [0,1,2],
    needle = 1,
    index = contains.call(myArray, needle); // true

CodePen の検証/使用法

于 2009-07-25T08:22:43.500 に答える
922

これは通常、indexOf() メソッドの目的です。あなたは言うでしょう:

return arrValues.indexOf('Sam') > -1
于 2009-07-25T08:25:53.383 に答える
47

tl;dr

function includes(k) {
  for(var i=0; i < this.length; i++){
    if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
      return true;
    }
  }
  return false;
}

function includes(k) {
  for(var i=0; i < this.length; i++){
    if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
      return true;
    }
  }
  return false;
}

function log(msg){
  $('#out').append('<div>' + msg + '</div>');  
}

var arr = [1, "2", NaN, true];
arr.includes = includes;

log('var arr = [1, "2", NaN, true];');
log('<br/>');
log('arr.includes(1): ' + arr.includes(1));
log('arr.includes(2): ' + arr.includes(2));
log('arr.includes("2"): ' + arr.includes("2"));
log('arr.includes(NaN): ' + arr.includes(NaN));
log('arr.includes(true): ' + arr.includes(true));
log('arr.includes(false): ' + arr.includes(false));
#out{
  font-family:monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=out></div>

より長い答え

この質問は、組み込みオブジェクトを拡張するかどうかに関するものではないことはわかっていますが、OP の試みとこの回答に対するコメントは、その議論を強調しています。2013 年 2 月 12 日の私のコメントは、この議論の概要を説明する記事を非常によく引用していますが、リンクが壊れており、時間がかかりすぎて元のコメントを編集できないため、ここに含めます.

組み込みArrayオブジェクトをメソッドで拡張しようとしている場合、おそらくこれを行うための最良かつ最も責任ある方法は、 MDNcontainsからこのポリフィルを使用することです。(プロトタイプの継承に関する MDN 記事のこのセクションも参照してください。「組み込みのプロトタイプを拡張する唯一の正当な理由は、新しい JavaScript エンジンの機能をバックポートすることです。たとえば、Array.forEach などです。」 )

if (!Array.prototype.includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    'use strict';
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

厳密な平等を望んでいませんか、それとも選択したいですか?

function includes(k, strict) {
  strict = strict !== false; // default is true
  // strict = !!strict; // default is false
  for(var i=0; i < this.length; i++){
    if( (this[i] === k && strict) || 
        (this[i] == k && !strict) ||
        (this[i] !== this[i] && k !== k)
    ) {
      return true;
    }
  }
  return false;
}
于 2011-09-15T20:03:07.603 に答える
20

ECMA 5 にアクセスできる場合は、someメソッドを使用できます。

MDN SOME メソッド リンク

arrValues = ["Sam","Great", "Sample", "High"];

function namePresent(name){
  return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"

arrValues.some(namePresent, 'Sam');
=> true;

ECMA 6 にアクセスできる場合は、includesメソッドを使用できます。

MDN にはメソッド リンクが含まれています

arrValues = ["Sam","Great", "Sample", "High"];

arrValues.includes('Sam');
=> true;
于 2015-07-31T15:46:12.593 に答える
18

IE の indexOf の実装を考えると (まぶたのないことで説明されているように):

Array.prototype.contains = function(obj) {
    return this.indexOf(obj) > -1;
};
于 2009-07-25T09:12:42.557 に答える
12

_.indexOf メソッドを使用するか、Underscore.js ライブラリ全体をアプリに含めたくない場合は、その方法を見て必要なコードを抽出できます。

    _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i = 0, l = array.length;
    if (isSorted) {
      if (typeof isSorted == 'number') {
        i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
      } else {
        i = _.sortedIndex(array, item);
        return array[i] === item ? i : -1;
      }
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
    for (; i < l; i++) if (array[i] === item) return i;
    return -1;
  };
于 2013-01-11T16:54:31.583 に答える
6

提供された答えは私にはうまくいきませんでしたが、それは私にアイデアを与えました:

Array.prototype.contains = function(obj)
    {
        return (this.join(',')).indexOf(obj) > -1;
    }

グループを超えて同じアイテムが一致する可能性があるため、完全ではありません。私の例のように

var c=[];
var d=[];
function a()
{
    var e = '1';
    var f = '2';
    c[0] = ['1','1'];
    c[1] = ['2','2'];
    c[2] = ['3','3'];
    d[0] = [document.getElementById('g').value,document.getElementById('h').value];

    document.getElementById('i').value = c.join(',');
    document.getElementById('j').value = d.join(',');
    document.getElementById('b').value = c.contains(d);
}

それぞれ 1 と 2 を含む 'g' フィールドと 'h' フィールドを使用してこの関数を呼び出すと、結合の結果の文字列が 1,1,2,2,3,3 であるため、引き続き検索されます。

私の状況では、このような状況に遭遇することは疑わしいので、これを使用しています。他の誰かが選択した答えを機能させることができなかった場合に備えて、共有すると思いました。

于 2011-05-24T18:09:42.877 に答える
2
function setFound(){   
 var l = arr.length, textBox1 = document.getElementById("text1");
    for(var i=0; i<l;i++)
    {
     if(arr[i]==searchele){
      textBox1 .value = "Found";
      return;
     }
    }
    textBox1 .value = "Not Found";
return;
}

このプログラムは、指定された要素が見つかったかどうかをチェックします。Id text1 はテキストボックスの ID を表し、searchele は検索対象の要素を表します (ユーザーから取得)。インデックスが必要な場合は、i 値を使用します

于 2014-07-24T08:40:19.047 に答える
1

関数の最も簡単な解決策は、contains次のような関数です。

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
}

ただし、これをスタンドアロン関数にするのではなく、ヘルパー ライブラリの一部にするのが理想的です。

var helper = {};

helper.array = {
    contains : function (haystack, needle) {
        return !!~haystack.indexOf(needle);
    }, 
    ...
};

さて、あなたがまだ IE<9 をサポートする必要があり、したがって に頼ることができない不運な人の 1 人である場合は、MDN から取得したindexOfこのpolyfillを使用できます。

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }
    var o = Object(this);
    var len = o.length >>> 0;
    if (len === 0) {
      return -1;
    }
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }
    if (n >= len) {
      return -1;
    }
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    while (k < len) {
      if (k in o && o[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}
于 2016-02-26T00:10:44.223 に答える
-7

私はシンプルさを好みます:

var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}
于 2014-05-06T07:02:44.687 に答える