首页 > 解决方案 > 是否可以在 Javascript 中动态添加方法?

问题描述

嘿,我正在做一个如下所示的 firebase 数据库调用:

db.collection("posts").where("location", "==", location)
    .get().then((querySnapshot) => {
        [...]
    })

用户可以指定他想从哪些国家获得帖子(.where()方法就是为此)。但他也可以选择所有国家,所以在这种情况下不再需要该方法。有没有办法动态添加方法?

像这样的东西:

db.collection("posts")if(location != "all"){.where("location", "==", location)}
    .get().then((querySnapshot) => {
        [...]
    })

标签: javascriptfunction

解决方案


你可以使用一个函数

const addLocationCondition = (collection, location) => 
    location === "all" ? collection : collection.where('location', '==', location);

addLocationCondition(db.collection('posts'), location).get()...

推荐阅读