我有一个手动键入的数据库,其中有一个对象,其中包含类别和每个类别的单词列表,如下所示:
var words =
{
sports: [
'baseball', 'football', 'volleyball', 'basketball', 'soccer'],
animals: [
'dog', 'cat', 'elephant', 'crocodile', 'bird'],
entertainment: [
'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}
我的HTML有一个bootstrap下拉列表,它将显示基于该列表的所有类别。我让代码将类别的值作为字符串单击:如下所示:
$(document).on('click', '.dropdown-menu li a', function () {
var selectedCategory;
selectedCategory = $(this).text();
//setting value of category to global variable
categorySelected = selectedCategory;
});
我需要能够从该值中找到我的数据库中的键。问题是我不能访问单词。“动物”我需要去掉字符串中的引号,才能得到这样的单词列表: words.animals
我该怎么做呢?我尝试过replace(),但它不起作用。
发布于 2017-07-07 02:02:19
您似乎正在尝试访问与words
对象中的类别相对应的值列表。键可以是字符串,所以words['animals']
就是一个获取动物列表的例子。
JavaScript还允许将变量用作键,因此您可以按如下方式访问它:
words[categorySelected]
发布于 2017-07-07 02:05:09
您可以将文本(下拉列表中的选定值)传递给函数以查找密钥
var words = {
sports: [
'baseball', 'football', 'volleyball', 'basketball', 'soccer'
],
animals: [
'dog', 'cat', 'elephant', 'crocodile', 'bird'
],
entertainment: [
'netflix', 'movies', 'music', 'concert', 'band', 'computer'
]
}
// function to find the key
function findKey(selText) {
//loop through the object
for (var keys in words) {
//get the array
var getArray = words[keys]
//inside each array check if the selected text is present using index of
if (getArray.indexOf(selText) !== -1) {
console.log(keys)
}
}
}
findKey('music')
https://stackoverflow.com/questions/44955940
复制相似问题