我不确定我是否采用了正确的方法,我的做法很像类(class)风格。有没有办法使用 loadProducts(data)
在对象中加载数据,这样我就可以调用 orderLines.getItemsType()
const orderProducts = {
loadProducts: function(data) {
//Load data into orderProducts object?
},
getItemsType: function(type) {
// return data
}
};
用法:
const items = orderProducts.getItemsType(['abc', 'ddd']);
注意:它是针对 node.js 的,不是针对浏览器的。
最佳答案
首先,您要将产品保存到属性中。我们将使用一些虚拟数据加载该属性。
然后我们可以使用 filter 过滤数据并测试该项目是否在 products 数组中,如下所示:
const orderProducts = {
// The list of products
products: [],
// The products to load
loadProducts: function(...data) {
this.products.push(...data)
},
// Get items passed in
getItemsType: function(...type) {
return this.products.filter(p => type.includes(p))
}
}
orderProducts.loadProducts('abc', '123', '111', 'ddd')
const items = orderProducts.getItemsType('abc', 'ddd')
console.log(items)
关于javascript - 在对象中加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429996/