这是我在StackOverflow上的第一篇文章。问候!
我是一名学习JavaScript和CoffeeScript的绝对初学程序员。
我正在编写一个递归函数来搜索对象,只是作为一种学习练习。
我希望该功能能够做到:
它目前的作用:
这是我的CoffeeScript:
meats =
a: "chickens"
b: "bacons"
c: "hams"
d: "salamis"
e: "beefs"
meatSearch = (dict, key) ->
if dict is key
then console.log "found #{dict.item}"
else if dict.sub
then meatSearch dict.sub, key
else console.log "item not found"
meatSearch meats, "b"
答案 0 :(得分:1)
首先,我认为示例数据应该更具递归性。只有一层,很难递归
第二:不清楚为什么要搜索一个项目(这是一个键值对)以及你期望的返回值。所以我稍微更改了您的示例以返回在键上定义的值
meats =
a: "chickens"
b:
b1: "bacon"
b2: "Schinken"
b3: "Sunka"
s:
s1: "French Salami"
s2: "Italian Salami"
e: "beefs"
search = (dict, key) ->
#check if dict is not an object and return imediately
return null if dict != Object(dict)
#get value of key
result = dict[key]
# return value if key is found
return result if result
#else iterate over keys and call search recursively for the value
for k of dict
console.log "#{k}: #{dict[k]}"
result = search dict[k], key
# return as soon as something is found
return result if result
#return null if nothing found
return null
console.log search meats, "b3" #should return <<Sunka>>
答案 1 :(得分:0)
尝试这样的事情[使用javascript,而不是咖啡抱歉]:
var index = 0;
var meats = {
0:'chickens',
1:'bacons',
2:'hams',
3:'salamis',
4:'beefs'
};
searchMeats: function(object, item) {
console.log(object,item);
if (object[index] === item) {
console.log('found ' + item);
} else if (object[index+1]) {
delete object[index];
index = index + 1;
searchMeats(object, item);
} else {
console.log('item not found');
}
};
searchMeats(meats, "hams");
它不是超级漂亮,但它使用递归!