代码错误,请帮忙-拆分字符串,并返回每个单词JS的长度

问题描述 投票:-1回答:3
function getWordLengths(str) {

return str.split(' ').map(words => words.length)
}

我的错误是

AssertionError:预期[0]等于[]+预期-实际

  -[
  -  0
  -]
  +[]

t('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]);
});
javascript arrays
3个回答
0
投票
it("returns [] when passed an empty string", () => { expect(getWordLengths("")).to.eql([0]); });

。to.eql([0])不是([])


0
投票

您可以使用类似这样的内容:

function getWordLengths(str) {
  return str.split(' ').map(words => str.length > 1 ? words.length : str.length);
}

console.log( getWordLengths("") );
console.log( getWordLengths("Hi") );
console.log( getWordLengths("Hi there how are you") );

0
投票

str.split(' ')返回一个包含1个项目的数组,其长度为0。这就是为什么您的测试用例似乎失败的原因。当str为空时,您将不得不调整测试用例或返回一个空数组。

expect(getWordLengths('')).to.eql([]);

expect(getWordLengths('')).to.eql([0]);
© www.soinside.com 2019 - 2024. All rights reserved.