Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript distinguish a function in an object

Having an object like this:

var a = {

  b: "string",
  c: function(){
    return "i return a string"; 
  }    
}

Doing

for (var key in a) {
    console.log(typeof key);
};

Returns "string", "string" since b is a string and c returns a string.

Is there afunction that returns c -> function?

like image 709
Matteo Pagliazzi Avatar asked Jul 31 '26 02:07

Matteo Pagliazzi


1 Answers

Returns "string", "string" since b is a string and c returns a string.

No. The reason it returns string, is that the attribute name b and the attribute name c are both strings; you're iterating over the keys of the object, not their values right now.

You could introduce attribute d, which was a function which returned a number or boolean, and you'd still get string.

Instead, enumerate over the values themselves;

for (var x in a) {
    console.log(typeof a[x] );
};
like image 91
Matt Avatar answered Aug 02 '26 16:08

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!