There is a variable v in my program, and I want to check if its property p contains a sub string sub. I could write a code like follows:
if (v.p.indexOf('sub') !== -1) {
// do something here
}
However, I have some doubts when seeing this code:
- What if
vis never declared - What if the property
pdoes not exist inv? - What if
v.pisnullorundefined? - What if
v.pis not a string
I want all the above cases not to raise errors in my code, and only do something here when v.p exists and contains a string that contains sub.
Does anyone know how to write this code correctly?
v?.p?.indexOf, please post an answer...