简体   繁体   English

为什么我的地图方法返回未定义?

[英]Why my map method is returning undefined?

I am really focusing on this problem, I can not find any mistake in my code.我真的很关注这个问题,我在我的代码中找不到任何错误。 I just want the array to contain the inner text of the paragraphs which has the class of true.我只希望数组包含具有 true 类的段落的内部文本。 Thanks in advance.提前致谢。

 function x() { let correct = document.querySelectorAll( `#circle p` ); let pArr = Array.prototype.slice.call(correct); let pCorrectArr = pArr.map(cur => { if (cur.classList.contains("true")) { const innerText = cur.innerText; return innerText; } }); return pCorrectArr; } console.log(x());
 <div id="circle"> <p>Google</p> <p class="true">Facebook</p> <p>Microsoft</p> </div>

Map would return an array with the same number of elements as the source array. Map 将返回一个与源数组具有相同元素数的数组。 Hence in your case, when you do not enter the if condition, you return "nothing".因此,在您的情况下,当您不输入if条件时,您将返回“无”。 Javascript assumes a function which has returned nothing to have returned undefined . Javascript 假设一个没有返回任何内容的函数返回了undefined

In your example, your if condition returns a string , while the other case just returns undefined .在您的示例中,您的 if 条件返回一个string ,而另一种情况只返回undefined This is the reason you're seein undefined mixed with your expected strings.这就是您看到undefined与您预期的字符串混合的原因。

You could use reduce instead to achieve what you want, reduce allows you to iterate over an array and create your own response.你可以使用reduce来实现你想要的, reduce允许你迭代一个数组并创建你自己的响应。 (you could return an array with more items, fewer items or an object that is not an array itself 😊) (您可以返回一个包含更多项、更少项或一个不是数组本身的对象的数组😊)

Here is your example code modified to work with reduce the way you want it.这是您修改后的示例代码,以reduce您想要的方式。 I'd suggest reading up on reduce here .我建议在这里阅读reduce

 function x() { let correct = document.querySelectorAll( `#circle p` ); let pArr = Array.prototype.slice.call(correct); let pCorrectArr = pArr.reduce(function(acc, cur){ if (cur.classList.contains("true")) { const innerText = cur.innerText; acc.push(innerText); } return acc; }, []); return pCorrectArr; } console.log(x());
 <div id="circle"> <p>Google</p> <p class="true">Facebook</p> <p>Microsoft</p> </div>

You could filter and return innerText by mapping this property.您可以通过映射此属性来过滤并返回innerText

Array#map returns another value for every item, but does not filter an array. Array#map为每个项目返回另一个值,但不过滤数组。

For this case, take Array#filter and add a mapping for the wanted property.对于这种情况,使用Array#filter并为所需属性添加映射。

 function x() { let correct = document.querySelectorAll('#circle p'); // no need for template strings return Array.prototype.slice .call(correct) .filter(cur => cur.classList.contains("true")) // filter .map(({ innerText }) => innerText); // map } console.log(x());
 <div id="circle"> <p>Google</p> <p class="true">Facebook</p> <p>Microsoft</p> </div>

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

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