In the array of elements known as my object idAry, each element has a property called msisdn_id
. The array contains 4 objects. While looping through them, if the ID matches the second ID in the loop, it correctly falls into the else clause. However, trying to access IDs of elements that are one position before or after the current element results in an error stating
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'msisdn_id' of undefined"
. It's puzzling why this property is suddenly undefined when I'm clearly iterating through its adjacent elements as well.
The code snippet in question is:
for (let [index, val] of idAry.entries()) {
console.log("index is:" + index);
console.log("val[index].msisdn_id:" + val[index].msisdn_id);
if(id == val[index].msisdn_id){
console.log("id found:" + val[index].msisdn_id);
if( index == 0 ){
//no left button
console.log("index == 0: " + val[index + 1].msisdn_id);
this.rightId = val[index + 1].msisdn_id;
}
else if (index == (val.length - 1)) {
//no right button
console.log("else if: " + val[index - 1].msisdn_id);
this.leftId = val[index - 1].msisdn_id;
}
else {
console.log("both LR: " + val[index - 1].msisdn_id + "," + val[index + 1].msisdn_id);
this.leftId = val[index - 1].msisdn_id;
this.rightId = val[index + 1].msisdn_id;
}
break;
}
}
The output generated looks like this:
length of ary is:4
TerminalProfileReport.vue?3387:400 index is:0
TerminalProfileReport.vue?3387:401 val[index].msisdn_id:111
TerminalProfileReport.vue?3387:400 index is:1
TerminalProfileReport.vue?3387:401 val[index].msisdn_id:222
TerminalProfileReport.vue?3387:403 id found:222
A correction was made to the output which initially displayed val[index]
. The updated code appears as follows:
for (let [index, val] of idAry.entries()) {
console.log("index is:" + index);
console.log("idAry[index].msisdn_id:" + val.msisdn_id);
if(id == val.msisdn_id){
console.log("id found:" + val.msisdn_id);
if( index == 0 ){
//no left button
console.log("index == 0: " + idAry[index + 1].msisdn_id);
this.rightId = idAry[index + 1].msisdn_id;
}
else if (index == (idAry.length - 1)) {
//no right button
console.log("else if: " + idAry[index - 1].msisdn_id);
this.leftId = idAry[index - 1].msisdn_id;
}
else {
console.log("both LR: " + idAry[index - 1].msisdn_id + "," + idAry[index + 1].msisdn_id);
this.leftId = idAry[index - 1].msisdn_id;
this.rightId = idAry[index + 1].msisdn_id;
}
break;
}
}