简体   繁体   English

使用map返回一个空数组,而不是[0]零

[英]Using map to return an empty array instead of [0] zero

I have some working code that will take a string of words and return an array of the length of each word. 我有一些工作代码,它将使用一串单词并返回每个单词长度的数组。 For example: 例如:

let str = "hello world" returns [5, 5]

My issue is if str = "" (empty) it will return [0] instead of [] (empty array) which is what I'd like it to do. 我的问题是,如果str =“”(空),它将返回[0]而不是[](空数组),这是我想要的。 Does anyone have any ideas how I can alter my code to return this? 有谁知道如何更改代码以返回此代码? Thank you! 谢谢!

const arr = str.split(' ');
return arr.map(words => words.length);

You can return an empty array if the string is equal to '' (empty string): 如果字符串等于'' (空字符串),则可以返回一个空数组:

 function count(str) { return (str === '') ? [] : str.split(' ').map(({length}) => length); } console.log(count('hello world')); console.log(count('')); 

Add a filter at the end. 在末尾添加一个filter

 const str = ""; const arr = str.split(' '); console.log(arr.map(words => words.length).filter(count => count != 0)); 

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

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