I'm following the solution from https://stackoverflow.com/a/519157/18736427.
However, the console gives me an error that the object I wanna test is undefined...
I wanna test if the object exists, if not, then console.log('False');, but it gives me an error of 'undefined'
Therefore the code after the check cannot be executed...How do I fix this?
const btn = document.querySelector('.test');
//const data1 = {
//apple: 'red'
//}
const data2 = {
banana: 'yellow'
}
btn.addEventListener('click', function() {
if (typeof data1['apple'] !== 'undefined') {
console.log('Yes');
}
console.log('False');
});
<button class="test">Check</button>
try:
const btn = document.getElementsByClassName('test');
if (typeof data["apple"] !== 'undefined') {
console.log('Yes');
}
you should use data.apple or data["apple"].
Check if you really need to provide red and apple variables.
Instead use a strings for keys
const btn = document.querySelector('.test');
const data = {
apple: "red"
}
btn.addEventListener('click', function() {
if (typeof data["apple"] !== 'undefined') {
console.log('Yes');
}
console.log('False');
});
If a object variable does not definied, the javascript really do not throw error. But if you write the red variable, the browser try assigns the real value the red variable. So,
the method really works: the red varible undefinied.
const btn = document.querySelector('.test');
const data = {
//do not define apple
}
btn.addEventListener('click', function() {
if (typeof data['apple'] !== 'undefined') {
console.log('Yes');
}
console.log('False');
});
<button class="test">Check</button>