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

问题描述 投票:0回答:1

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

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))

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

所以我需要编写一个函数,以获取将通过这些条件的数组上每个单词的长度,它(“传递空字符串时返回[]”,()=> {Expect(...

javascript arrays numbers
1个回答
1
投票

对于空字符串,您将获得[ "" ],并且.map将返回[ 0 ]

© www.soinside.com 2019 - 2024. All rights reserved.