简体   繁体   English

为什么我的函数总是返回未定义的?

[英]Why does my function always return undefined?

I have written a function to search in a nested object. 我写了一个函数来搜索嵌套对象。 The problem is that it returns undefined instead of the expected result, that is correctly logged in the console. 问题是它返回undefined而不是预期结果,该结果已正确记录在控制台中。 Whats going on there? 发生什么事了?

 const in1 = [1, 2]; const in2 = [1, 2]; const vDOM = { 1: { ref: in1, children: { 2: { ref: in2, children: {} } } } } const findVDOMNode = function(instance, vDOM) { const keys = Object.keys(vDOM); const foundKey = keys.find(key => vDOM[key].ref === instance); //console.log(foundKey, vDOM, "FK"); if (!keys.length) { console.log('no keys'); return; } if (foundKey) { console.log('found', vDOM[foundKey]); return true; //vDOM[foundKey]; }; keys.map(key => findVDOMNode(instance, vDOM[key].children)); } console.log('res: ', findVDOMNode(in2, vDOM)); 

Live example: https://stackblitz.com/edit/js-dapzsy 实时示例: https//stackblitz.com/edit/js-dapzsy

Just add return at the end. 只需在末尾添加return

return keys.map(key =>
    findVDOMNode(instance, vDOM[key].children));

You could take the values of the object and check it against the instance. 您可以获取对象的值并对照实例进行检查。 If an object is found, check the object as well. 如果找到了对象,请同时检查该对象。 For iterating use some with short circuit, if the instance is found. 如果发现实例,则使用some短路进行迭代。

 const in1 = [1, 2], in2 = [1, 2], vDOM = { 1: { ref: in1, children: { 2: { ref: in2, children: {} } } } }, findVDOMNode = (instance, vDOM) => Object .values(vDOM) .some(v => v === instance || v && typeof v === 'object' && findVDOMNode(instance, v) ); console.log('res: ', findVDOMNode(in2, vDOM)); 

it looks like you are missing a return statement on the map in the last line of the function 好像您在函数的最后一行中缺少地图上的return语句

 const in1 = [1, 2]; const in2 = [1, 2]; const vDOM = { 1: { ref: in1, children: { 2: { ref: in2, children: {} } } } } const findVDOMNode = function(instance, vDOM) { const keys = Object.keys(vDOM); const foundKey = keys.find(key => vDOM[key].ref === instance); //console.log(foundKey, vDOM, "FK"); if (!keys.length) { console.log('no keys'); return; } if (foundKey) { console.log('found', vDOM[foundKey]); return true; //vDOM[foundKey]; }; ///added this return statement return keys.map(key => findVDOMNode(instance, vDOM[key].children)); } console.log('res: ', findVDOMNode(in2, vDOM)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM