{ expect(get-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:25:11 27 4
gpt4 key购买 nike

所以我需要编写一个函数来获取数组中将通过这些条件的每个单词的长度

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]

关于javascript - 当传递空字符串时返回 [] ,当传递多个单词时返回长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com