I usually use Python for machine learning programming, but I also need to do around the screen, and at that time, is it the code that judges the JavaScript dictionary with the if
statement? I thought. Until then, it's a misunderstanding.
I wrote the following if
statement to determine if a dictionary is empty in Python. If x
is an empty dictionary or null, it will be False
.
sample.py
x = {}
if x:
print("x is not empty");
else:
print("x is empty");
Execution result
x is empty
On the other hand, in JavaScript, it is True
in the case of an empty dictionary.
sample.js
var x = {};
if (x) {
console.log("x is not empty");
} else {
console.log("x is empty");
}
x is not empty
There seem to be various ways to determine if it is empty, but it seems that it can be done by checking the number of keys with Object.keys (x)
.
sample.js
var x = {};
if (Object.keys(x).length) {
console.log("x is not empty");
} else {
console.log("x is empty");
}
I inadvertently thought and coded it in the same way as Python, and I was worried that it wouldn't work ...
It is easy to understand whether the judgment result of JavaScript if (x)
is True/False
for each object.
-[JavaScript] Judgment of null, undefined, 0, empty string (”), false, etc.
Recommended Posts