Określ, czy tablica zawiera wartość [duplikat]
To pytanie ma już odpowiedź tutaj:
- Jak sprawdzić, czy tablica zawiera obiekt w JavaScript? 41 odpowiedzi
Muszę określić, czy w tablicy istnieje wartość.
Używam następującej funkcji:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
Powyższa funkcja zawsze zwraca false.
Wartości tablicy i wywołanie funkcji jest jak poniżej:
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
18 answers
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;
};
Możesz go użyć TAK:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-05 02:46:56
JQuery ma do tego funkcję użyteczności:
$.inArray(value, array)
Zwraca indeks value
w array
. Zwraca -1
Jeśli array
nie zawiera value
.
Zobacz także Jak sprawdzić, czy tablica zawiera obiekt w JavaScript?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:26
Do tego służy metoda indexOf (). Powiedziałbyś:
return arrValues.indexOf('Sam') > -1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-04 19:23:36
Array.prototyp.includes ()
W ES2016 jest Array.prototype.includes()
.
Metoda
includes()
określa, czy tablica zawiera określony element, zwracając odpowiedniotrue
lubfalse
.
Przykład
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
Wsparcie
Zgodnie z KANGAX i MDN obsługiwane są następujące platformy:
- Chrome 47
- Edge 14
- Firefox 43
- Opera 34
- Safari 9
- węzeł 6
Wsparcie można rozszerzyć za pomocą Babel (za pomocą babel-polyfill
) lub core-js
. MDN zapewnia również polyfill :
if (![].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;
};
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-24 09:13:22
Prawie zawsze bezpieczniej jest używać biblioteki takiej jak lodash po prostu ze względu na wszystkie problemy z kompatybilnością między przeglądarkami i wydajnością.
Efektywność, ponieważ możesz mieć gwarancję, że w danym momencie, bardzo popularna biblioteka, taka jak underscore, będzie miała najbardziej efektywną metodę realizacji funkcji użytkowej takiej jak ta.
_.includes([1, 2, 3], 3); // returns true
Jeśli martwisz się o zawartość, która zostanie dodana do Twojej aplikacji poprzez włączenie całej biblioteki, wiedz, że możesz Dołącz funkcjonalność oddzielnie:
var includes = require('lodash/collections/includes');
Uwaga: w starszych wersjach lodash było to _.contains()
, a nie _.includes()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-04 17:39:20
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;
}
Przykład
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>
Dłuższa Odpowiedź
Wiem, że to pytanie nie dotyczy tak naprawdę tego, czy rozszerzać obiekty wbudowane, czy nie, ale próba OP i komentarze do tej odpowiedzi podkreślają tę debatę. Mój komentarz z Feb 12, '13 cytuje artykuł, który bardzo dobrze opisuje tę debatę, jednak ten link się zepsuł i nie mogę edytować oryginalnego komentarza, ponieważ za dużo czasu minęło, więc dołączam to tutaj.
Jeśli chcesz rozszerzyć wbudowany obiekt Array
metodą contains
, prawdopodobnie najlepszym i najbardziej odpowiedzialnym sposobem na to byłoby użycie tego polyfill z MDN. (Zobacz także ten rozdział artykułu MDN na temat dziedziczenia prototypów, który wyjaśnia, że " jedynym dobrym powodem rozszerzenia wbudowanego prototypu jest backport funkcji nowszych silników JavaScript; na przykład Array.forEach, itd.")
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;
};
}
Nie chcesz surowej równości, czy chcesz wybrać?
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-15 16:55:54
Od ECMAScript6 można użyć Set
:
var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-13 01:40:05
Mój mały wkład:
function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-25 23:43:55
Biorąc pod uwagę implementację indexOf dla IE (opisaną przez eyelessness):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-05 13:44:32
Jeśli masz dostęp do ECMA 5 możesz użyć jakiejś metody .
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;
Jeśli masz dostęp do ECMA 6, możesz użyć metody includes .
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 15:26:42
Możesz użyć _.metoda indexOf lub jeśli nie chcesz zawierać całego podkreślenia.biblioteka js w Twojej aplikacji, możesz spojrzeć Jak to zrobili i wyodrębnić potrzebny kod.
_.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;
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-11 16:54:31
Inną opcją byłoby użycie Array.some
(jeśli dostępne ) w następujący sposób:
Array.prototype.contains = function(obj) {
return this.some( function(e){ return e === obj } );
}
Funkcja anonimowa przekazana do Array.some
zwróci true
wtedy i tylko wtedy, gdy w tablicy znajduje się element identyczny z obj
. W przypadku braku takiego elementu, funkcja nie zwróci true
dla żadnego z elementów tablicy, więc Array.some
zwróci false
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-08 00:44:20
Wow, jest wiele świetnych odpowiedzi na to pytanie.
Nie widziałem takiego, który przyjmuje podejście reduce
więc dodam:
var searchForValue = 'pig';
var valueIsInArray = ['horse', 'cat', 'dog'].reduce(function(previous, current){
return previous || searchForValue === current ? true : false;
}, false);
console.log('The value "' + searchForValue + '" is in the array: ' + valueIsInArray);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-07 16:20:19
Udzielona odpowiedź nie zadziałała na mnie, ale dała mi pomysł:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
To nie jest idealne, ponieważ przedmioty, które są takie same poza grupami, mogą skończyć się dopasowaniem. Takie jak mój przykład
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);
}
Kiedy wywołuję tę funkcję z polami " g " I " h " zawierającymi odpowiednio 1 i 2, nadal ją Znajduje, ponieważ wynikowy ciąg z połączenia wynosi: 1,1,2,2,3,3
Ponieważ wątpliwe jest w mojej sytuacji, że natknę się na tego typu sytuacje, używam tego. Myślałem, że podzielę się okryciem, że ktoś inny nie może sprawić, że wybrana odpowiedź zadziała.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-24 18:09:42
Używanie tablicy .funkcja map, która wykonuje funkcję dla każdej wartości w tablicy wydaje mi się najczystsza.
Ta metoda może działać dobrze zarówno dla prostych tablic, jak i dla tablic obiektów, gdzie trzeba sprawdzić, czy w tablicy obiektów istnieje klucz/wartość.
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-06 06:30:21
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;
}
Ten program sprawdza czy dany element został znaleziony czy nie. Id text1 reprezentuje id textboxa, a searchele reprezentuje element, który ma być wyszukiwany (got fron user); jeśli chcesz indeks, użyj I value
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-06 14:04:20
Najprostszym rozwiązaniem dla contains
funkcji, byłaby funkcja, która wygląda tak:
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
}
Najlepiej byłoby, gdyby nie była to samodzielna funkcja, ale część biblioteki pomocniczej:
var helper = {};
helper.array = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Teraz, jeśli zdarzy ci się być jednym z tych pechowych ludzi, którzy nadal muszą wspierać IEindexOf, możesz użyć tego polyfill , który dostałem z MDN : {]}
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;
};
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-26 00:10:44
Wolę prostotę:
var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-06 07:02:44