![](/img/trans.png)
[英]How do I check in JavaScript if a value exists at a certain array index?
[英]How to check if an array index exists or not in 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
數組。 我仍然無法使用上面的代碼檢測到不存在的索引。
使用typeof arrayName[index] === 'undefined'
IE
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");
}
如果我錯了,請有人糾正我,但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
這正是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! }
這些天我會利用 ecmascript 並像那樣使用它
return myArr?.[index]
我不得不將 techfoobar 的答案包裝在try
.. catch
塊中,如下所示:
try {
if(typeof arrayName[index] == 'undefined') {
// does not exist
}
else {
// does exist
}
}
catch (error){ /* ignore */ }
...無論如何,這就是它在 chrome 中的工作方式(否則,代碼會因錯誤而停止)。
如果數組的元素也是簡單的對象或數組,你可以使用一些函數:
// 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')
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') }
如果您使用underscore.js,那么庫會隱藏這些類型的 null 和 undefined 檢查。
所以你的代碼看起來像這樣 -
var currentData = new Array();
if (_.isEmpty(currentData)) return false;
Ti.API.info("is exists " + currentData[index]);
return true;
它現在看起來更具可讀性。
這種方式在我看來是最簡單的。
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")
當試圖找出 JS 中是否存在數組索引時,最簡單、最短的方法是通過雙重否定。
let a = [];
a[1] = 'foo';
console.log(!!a[0]) // false
console.log(!!a[1]) // true
const arr = []
typeof arr[0] // "undefined"
arr[0] // undefined
如果布爾表達式
typeof arr[0] !== typeof undefined
為真則 0 包含在 arr 中
一行驗證。 最簡單的方法。
return !!currentData[index];
產出
var testArray = ["a","b","c"]
testArray[5]; //output => undefined
testArray[1]; //output => "b"
!!testArray[5]; //output => false
!!testArray[1]; //output => true
你可以簡單地使用這個:
var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
console.log(tmp[index] + '\n');
}else{
console.log(' does not exist');
}
(typeof files[1] === undefined)?
this.props.upload({file: files}):
this.props.postMultipleUpload({file: files widgetIndex: 0, id})
使用typeof
檢查數組中的第二項是否未定義並檢查undefined
if(typeof arrayName[index] == undefined) {
console.log("Doesn't exist")
}
else {
console.log("does exist")
}
這也可以正常工作,按類型針對undefined
進行測試。
if (currentData[index] === undefined){return}
測試:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; if (fruits["Raspberry"] === undefined){ console.log("No Raspberry entry in fruits!") }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.