Ответ 1
Используйте typeof arrayName[index] === 'undefined'
т.е.
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
Я работаю с 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
. Я все еще не могу обнаружить несуществующий элемент, используя приведенный выше код.
Используйте typeof arrayName[index] === 'undefined'
т.е.
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if (myArray.indexOf(searchTerm) === -1) {
console.log("element doesn't exist");
}
else {
console.log("element found");
}
Мне пришлось обернуть ответ Techfoobar в блоке try
.. catch
, например:
try {
if(typeof arrayName[index] == 'undefined') {
// does not exist
}
else {
// does exist
}
}
catch (error){ /* ignore */ }
... что как он работал в chrome, в любом случае (в противном случае код был остановлен с ошибкой).
Если элементы массива также являются простыми объектами или массивами, вы можете использовать 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;
}
});
Рассмотрим массив 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')
Кто-то, пожалуйста, поправьте меня, если я ошибаюсь, но AFAIK верно следующее:
hasOwnProperty
"унаследованный" от Object
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
Если вы используете underscore.js, то эти типы нулевой и undefined проверки скрываются библиотекой.
Итак, ваш код будет выглядеть так:
var currentData = new Array();
if (_.isEmpty(currentData)) return false;
Ti.API.info("is exists " + currentData[index]);
return true;
Теперь он выглядит намного читабельнее.
вы можете просто использовать это:
var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
console.log(tmp[index] + '\n');
}else{
console.log(' does not exist');
}
Этот способ, на мой взгляд, самый простой.
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');
}
}
Простой способ проверить элемент существует или нет
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")
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
//Array index exists
}else{
//Array Index does not Exists
}
Если вы ищете что-то подобное.
Вот следующий фрагмент
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
}
var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Banana") == -1){
console.log('item not exist')
} else {
console.log('item exist')
}
(typeof files[1] === undefined)?
this.props.upload({file: files}):
this.props.postMultipleUpload({file: files widgetIndex: 0, id})
Проверьте, не является ли второй элемент в массиве неопределенным, используя typeof
и проверьте наличие undefined
Это именно то, для чего предназначен оператор 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!
}
const arr = []
typeof arr[0] // "undefined"
arr[0] // undefined
Если логическое выражение
typeof arr[0] !== typeof undefined
верно, тогда 0 содержится в обр
При попытке выяснить, существует ли индекс массива в JS, самый простой и короткий способ сделать это - через двойное отрицание.
let a = [];
a[1] = 'foo';
console.log(!!a[0]) // false
console.log(!!a[1]) // true