javascript에서 배열 인덱스의 존재 여부를 확인하는 방법
티타늄을 사용하고 있는데 코드는 다음과 같습니다.
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");
}
요즘은 ecmascript를 활용해서 그렇게 쓰고 있다.
return myArr?.[index]
틀렸다면 정정해 주세요.AFIK는 다음과 같습니다.
- 어레이는 실제로는 JS에 가려져 있는 오브젝트일 뿐입니다.
- 그래서 그들은 시제품 방법을 가지고 있다.
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!
}
techfoobar의 답변을 한마디로 정리해야 했습니다.try
..catch
블록은 다음과 같습니다.
try {
if(typeof arrayName[index] == 'undefined') {
// does not exist
}
else {
// does exist
}
}
catch (error){ /* ignore */ }
어쨌든 크롬에서는 그렇게 동작합니다(코드가 에러로 정지했습니다).
어레이 a:
var a ={'name1':1, 'name2':2}
에 'name1'이 존재하는지 여부를 확인하려면 다음 명령을 사용하여 테스트합니다.in
:
if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
배열 요소도 단순한 개체 또는 배열인 경우 다음과 같은 기능을 사용할 수 있습니다.
// 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;
}
});
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
//Array index exists
}else{
//Array Index does not Exists
}
또, 이 동작도 양호하게 동작합니다.유형별로 테스트합니다.===
그에 반대하여undefined
.
if (array[index] === undefined){ return } // True
테스트:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
if (fruits["Cherry"] === undefined){
console.log("There isn't any cherry in the fruits basket :(")
}
또는 마찬가지로:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
if (!fruits["Cherry"]){
console.log("There isn't any cherry in the fruits basket :(")
}
// No errors:
if (fruits["Cherry"]){
console.log("There is some cherry in there!")
}
만약 당신이 이런 것을 찾고 있다면.
여기 다음 스니펫이 있습니다.
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')
}
1줄 검증가장 간단한 방법.
return !!currentData[index];
출력
var testArray = ["a","b","c"]
testArray[5]; //output => undefined
testArray[1]; //output => "b"
!!testArray[5]; //output => false
!!testArray[1]; //output => true
언더스코어.js를 사용하는 경우 이러한 유형의 null 및 정의되지 않은 검사는 라이브러리에 의해 숨겨집니다.
그래서 당신의 코드는 다음과 같습니다.
var currentData = new Array();
if (_.isEmpty(currentData)) return false;
Ti.API.info("is exists " + currentData[index]);
return true;
이제 훨씬 읽기 쉬워진 것 같아요.
아이템의 유무를 확인하는 간단한 방법
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 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');
}
}
어레이 인덱스가 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
If 부울식
typeof arr[0] !== typeof undefined
true이면 arr에 0이 포함됩니다.
간단하게 사용할 수 있습니다.
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")
}
언급URL : https://stackoverflow.com/questions/13107855/how-to-check-if-an-array-index-exists-or-not-in-javascript
'programing' 카테고리의 다른 글
입력 종료 잭슨 파서로 인해 매핑할 콘텐츠가 없습니다. (0) | 2022.10.18 |
---|---|
ElasticSearch를 MySQL과 통합하는 방법 (0) | 2022.10.08 |
MySQL에서 sqlalchemy 연결을 닫는 방법 (0) | 2022.10.08 |
DB에서 설정을 가져오는 함수에서 오류가 발생했습니다. (0) | 2022.10.08 |
포틀렛과 서블릿의 차이점은 무엇입니까? (0) | 2022.10.08 |