Подтвердить что ты не робот

Как проверить, существует ли элемент массива или нет в javascript?

Я работаю с Titanium, мой код выглядит так:

var currentData = new Array();

if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{   
    return false;
}

Я передаю индекс в массив currentData. Я все еще не могу обнаружить несуществующий элемент, используя приведенный выше код.

4b9b3361

Ответ 1

Используйте typeof arrayName[index] === 'undefined'

т.е.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}

Ответ 2

var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}

Ответ 3

Мне пришлось обернуть ответ Techfoobar в блоке try.. catch, например:

try {
  if(typeof arrayName[index] == 'undefined') {
    // does not exist
  }
  else {
  // does exist
  }
} 
catch (error){ /* ignore */ }

... что как он работал в chrome, в любом случае (в противном случае код был остановлен с ошибкой).

Ответ 4

Если элементы массива также являются простыми объектами или массивами, вы можете использовать some:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});

Ответ 5

Рассмотрим массив a:

var a ={'name1':1, 'name2':2}

Если вы хотите проверить, существует ли 'name1' в a, просто протестируйте его с помощью in:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')

Ответ 6

Кто-то, пожалуйста, поправьте меня, если я ошибаюсь, но AFAIK верно следующее:

  1. Массивы действительно просто объекты под капотом JS
  2. Таким образом, у них есть метод-прототип hasOwnProperty "унаследованный" от Object
  3. в моем тестировании hasOwnProperty может проверить, существует ли что-либо в индексе массива.

Таким образом, если вышеизложенное верно, вы можете просто:

const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

использование:

arrayHasIndex([1,2,3,4],4); выходы: false

arrayHasIndex([1,2,3,4],2); выходы: true

Ответ 7

Если вы используете underscore.js, то эти типы нулевой и undefined проверки скрываются библиотекой.

Итак, ваш код будет выглядеть так:

var currentData = new Array();

if (_.isEmpty(currentData)) return false;

Ti.API.info("is exists  " + currentData[index]);

return true;

Теперь он выглядит намного читабельнее.

Ответ 8

вы можете просто использовать это:

var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}

Ответ 9

Этот способ, на мой взгляд, самый простой.

var nameList = new Array('item1','item2','item3','item4');

// Using for loop to loop through each item to check if item exist.

for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1') 
{   
   alert('Value exist');
}else{
   alert('Value doesn\'t exist');
}

И, может быть, еще один способ сделать это.

nameList.forEach(function(ItemList)
 {
   if(ItemList.name == 'item1')
        {
          alert('Item Exist');
        }
 }

Ответ 10

Простой способ проверить элемент существует или нет

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

var myArray= ["Banana", "Orange", "Apple", "Mango"];

myArray.contains("Apple")

Ответ 11

var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}

Ответ 12

Если вы ищете что-то подобное.

Вот следующий фрагмент

var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(demoArray.includes(ArrayIndexValue)){
alert("value exists");
   //Array index exists
}else{
alert("does not exist");
   //Array Index does not Exists
}

Ответ 13

var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Banana") == -1){
    console.log('item not exist')
} else {
	console.log('item exist')
}

Ответ 14

(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Проверьте, не является ли второй элемент в массиве неопределенным, используя typeof и проверьте наличие undefined

Ответ 15

Это именно то, для чего предназначен оператор in. Используйте это так:

if (index in currentData) 
{ 
    Ti.API.info(index + " exists: " + currentData[index]);
}

принятый ответ неверен, он даст ложный отрицательный результат, если значение в index равно undefined:

const currentData = ['a', undefined], index = 1;

if (index in currentData) {
  console.info('exists');
}
// ...vs...
if (typeof currentData[index] !== 'undefined') {
  console.info('exists');
} else {
  console.info('does not exist'); // incorrect!
}

Ответ 16

const arr = []

typeof arr[0] // "undefined"

arr[0] // undefined

Если логическое выражение

typeof arr[0] !== typeof undefined

верно, тогда 0 содержится в обр

Ответ 17

При попытке выяснить, существует ли индекс массива в JS, самый простой и короткий способ сделать это - через двойное отрицание.

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // true