[英]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 所以我在cities.js
文件中有一个功能
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 如果我以这种方式访问if(cities.newyork){}
则true和false条件都可以,但是如果我以这种方式访问函数
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]
. 您要查找的语法是cities[city]
。 As is, your code is looking for a property of cities literally called 'city' 照原样,您的代码正在寻找字面上称为“ city”的城市的属性
You should use, cities[city]
. 您应该使用cities[city]
。 This is because, 这是因为,
In cities.city
, "city" will be considered as "key name". 在cities.city
,“ city”将被视为“键名”。 So it will transformed as cities["city"]
因此它将转变为cities["city"]
But in cities[city]
it will actually transform to cities["newyork"]
但是在cities[city]
它实际上将转变为cities["newyork"]
So always use, obj[dynamic_key_name]
. 因此,请始终使用obj[dynamic_key_name]
。 Access property with "."
使用"."
访问属性"."
only when you know the property name. 仅当您知道属性名称时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.