传递空字符串时返回 [],传递多个单词时返回长度



所以我需要编写一个函数来获取数组上每个单词的长度,该数组将传递这些条件

it("returns [] when passed an empty string", () => {
expect(getWordLengths("")).to.eql([]);
});
it("returns an array containing the length of a single word", () => {
expect(getWordLengths("woooo")).to.eql([5]);
});
it("returns the lengths when passed multiple words", () => {
expect(getWordLengths("hello world")).to.eql([5, 5]);
});
it("returns lengths for longer sentences", () => {
expect(getWordLengths("like a bridge over troubled water")).to.eql([
4,
1,
6,
4,
8,
5
]);

我最初的解决方案有效,但我想改用 .map。到目前为止,我得到了

let x = str.split(' ');
console.log(x.map(nums => nums.length))

但是当通过空数组传递时不会返回 []

对于空字符串,你会得到[ "" ].map将返回[ 0 ]

过滤掉0值:

str.split(" ").map(nums => nums.length).filter(e => e);

const getWordLengths = str => {
return str
.split(" ")
.map(nums => nums.length)
.filter(e => e);
};
console.log(getWordLengths("")); //? []
console.log(getWordLengths("woooo")); //? [5]
console.log(getWordLengths("hello world")); //? [5, 5]
console.log(getWordLengths("like a bridge over troubled water")); //? [4, 1, 6, 4, 8, 5]

相关内容

最新更新