简体   繁体   中英

check if module method exist in node js

I have a question similar to this question and has a slightly different problem.

So I have a function in cities.js file

module.exports = {


    newyork: function (latitude,longitude) {
        console.log("newyork is here");
} 

If I access this function this way if(cities.newyork){} then true and false condition works fine but If I access function this way

 var city = 'newyork';
    if(cities.city){
console.log("true");
}else{
console.log(false);
}

It always goes in else condition. Because cities names would be dynamic so I need this function to work. I have tried this way as well

if(typeof cities.city === 'function'){
      console.log("true");
    }else{
     console.log(false);
    }

Still no luck. Any help would be appreciated

The syntax you're looking for is cities[city] . As is, your code is looking for a property of cities literally called 'city'

You should use, cities[city] . This is because,

In cities.city , "city" will be considered as "key name". So it will transformed as cities["city"]

But in cities[city] it will actually transform to cities["newyork"]

So always use, obj[dynamic_key_name] . Access property with "." only when you know the property name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM