Reputation: 641
I went through some JS code last day, but I couldn't understand. Here is the code
var data = {
name : 'Mr John',
age : '29',
location : 'New York',
profession : 'Accoutant'
};
var allowedNull = [];
for (var i in data) {
if (!data[i])
{
if (allowedNull.indexOf(i) < 0)
{
console.log('Empty');
}
}
}
The script actually prints "Empty" in console if the data
has an empty property. I just wanted know, how it works by calling indexOf
on allowedNull
. Can somebody explain how this works.
Fiddle : Check
Upvotes: 0
Views: 2843
Reputation: 528
first of all the indexOf(i)
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
In this case the flow is:
//loop over data object
for (var i in data) {
//if the current property is empty/undefined
if (!data[i])
{
//and if this property is not present inside the allowedNull array
if (allowedNull.indexOf(i) < 0)
{
// print empty
console.log('Empty');
}
}
}
If you try to add in the data object the property test : ''
you'll get printed in the console Empty
but if you add test
inside the allowedNull array var allowedNull = ['test']
nothing will be printed.
Hope this can help! :)
Upvotes: 2