我正在使用 emberjs 来查找内容,但问题与 JS 相关性比 Ember 更多。
我有两个变量: var type = "stars"; var term =“5”
我的 API 中有一个名为 star 的属性。
当我这样做时:App.Response.find({stars: term});
我找到结果
但是,当我这样做时:App.Response.find({type: term});
我没有找到结果。我希望将其转换为 App.Response.find({stars: term})
因为 type
的值为 "stars"
我假设这是因为type
(值为stars
)没有被理解为哈希键?
最佳答案
确实 - 它不会评估对象键。如果您想动态创建该对象作为 {stars:5}
您可以这样做:
var obj = {};
obj[type] = term;//Using the array notation will cause JS to evaluate type to "stars" and use that as the key
//obj is now {stars:5}
App.Response.find(obj);
关于javascript - 如何将字符串转换为对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18385017/