请... 伙计们,我哪里出错了?
经典的字数统计算法:给定一个字符串数组,返回一个 Map ,每个不同的字符串都有一个键,值是该字符串在数组中出现的次数。
wordCount(["a", "b", "a", "c", "b"]) → {"a": 2, "b": 2, "c": 1}
wordCount(["c", "b", "a"]) → {"a": 1, "b": 1, "c": 1}
wordCount(["c", "c", "c", "c"]) → {"c": 4}
到目前为止我的代码
function wordCount(arrayOfStrings) {
const map = {};
const arr = arrayOfStrings;
for (let i = 0; i < arr.length; i++) {
let arr2 = arr.charAt(i);
if (arr.indexOf(arr2) === arr.lastIndexOf(arr2)) {
map.push({
arr: arr2
});
}
}
}
wordCount(["a", "b", "a", "c", "b"])
下面是我要通过的测试
test(`Expect the wordCount of ["one", "fish", "two", "fish", "red", "fish", "blue", "fish"] to equal {one: 1, fish: 4, two: 1, red: 1, blue: 1}`, () => {
expect(wordCount([ 'one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish' ])).toEqual({ one: 1, fish: 4, two: 1, red: 1, blue: 1 });
});
test(`Expect the wordCount of ["str", "hell", "str", "str"] to equal {str: 3, hell: 1}`, () => {
expect(wordCount([ 'str', 'hell', 'str', 'str' ])).toEqual({ str: 3, hell: 1 });
});
test(`Expect the wordCount of ["a", "b", "a", "c", "b"] to equal {"a": 2, "b": 2, "c": 1}`, () => {
expect(wordCount([ 'a', 'b', 'a', 'c', 'b' ])).toEqual({ a: 2, b: 2, c: 1 });
});
test(`Expect the wordCount of [1, "chair", "cane", "chair"] to equal {1: 1, chair: 2, cane: 1}`, () => {
expect(wordCount([ 1, 'chair', 'cane', 'chair' ])).toEqual({ 1: 1, chair: 2, cane: 1 });
});
test(`Expect the wordCount of ["ch", "chair", "cane", "chair", "ai", "ir"] to equal { ch: 1, chair: 2, cane: 1, ai: 1, ir: 1 }`, () => {
expect(wordCount([ 'ch', 'chair', 'cane', 'chair', 'ai', 'ir' ])).toEqual({ ch: 1, chair: 2, cane: 1, ai: 1, ir: 1 });
});
慕盖茨4494581
慕容708150
翻过高山走不出你
相关分类