How to check if an index exists in an array or not in VueJS?
June 20, 2022Hi Friends 👋,
Welcome To SortoutCode! ❤️
Today I am going to show you How do you check if an index exists in an array or not in VueJS.
Let’s start with the defining the array,
<script>
export default {
name: 'FirstComponent',
data() {
return{
names : ["Welcome","to","Sortcode","Sortoutcode"],
}
},
}
</script>
Data is used to define properties in a particular component. In a single-file component, data()
is a function that returns a set of properties that have been defined in the function.
we define the names array with some data.
when we console the names array index 3 and 4 it returns the Sortoutcode and undefined.
console.log(this.names[3]); // Sortoutcode
console.log(this.names[4]); // undefined
when we put this index access value syntax in if...else
and check whether we can know index exists or not.
<template>
<div>
<h1>Welcome to SortoutCode</h1>
</div>
</template>
<script>
export default {
name: 'FirstComponent',
data(){
return{
names : ["Welcome","to","Sortcode","Sortoutcode"],
}
},
mounted(){
if(this.names[2]){
console.log("names[2], ","Index Exist");
}else{
console.log("names[2], ",'Index Not Exist');
}
},
}
</script>
For now, let’s check the output.
Output
All the best 👍.