计算字符串中唯一单词的数量

3

下面我尝试将字符串数组传递给一个函数,该函数将唯一的单词添加到words数组中,如果该单词已经存在于数组中,则增加相应元素在count数组中的计数:

var words = [];
var counts = [];

calculate([a, b]);
calculate([a, c]);

function calculate(result) {
    for (var i = 0; i < result.length; i++) {
        var check = 0;
        for (var j = 0; i < tags.length; i++) {
            if (result[i] == tags[j]) {
                check = 1;
                counts[i] = counts[i] + 20;
            }
        }
        if (check == 0) {
            tags.push(result[i]);
            counts.push(20);
        }
        check = 0;
    }
}

然而,实际输出却是这样的:

单词 = a,b 数量 = 2,1

当我期望它是这样的: 单词 = a,b,c 数量 = 2,1,1

非常感谢您提前的任何帮助


3
你声明了一个 words 数组,但从未使用过。你使用了一个从未声明的 tags 数组。我猜它们应该是同一个数组吧? - flowstoneknight
3
你的第二个for循环有误了,应该遍历变量j。将j=0改为j=0; j < tags.length; j++ - Jindra Helcl
4个回答

2
将问题分解为具有良好命名的方法有助于您理清逻辑。请尝试以下步骤:
<script type="text/javascript">
var words = [];
var counts = [];
calculate(["a", "b"]);
calculate(["a", "c"]);
console.log(words);
console.log(counts);

function calculate(result) {
    for (var i=0; i<result.length; i++) {
        if (array_contains(words, result[i])) {
            counts[result[i]]++;
        } else {
            words.push(result[i]);
            counts[result[i]] = 1;
        }
    }
}

function array_contains(array, value) {
    for (var i=0; i<array.length; i++)
        if (array[i] == value)
            return true;
    return false;
}

</script>

输出:

["a", "b", "c"]
[]
a 2
b 1
c 1


1
一些地方有问题,这是可工作的代码:

var words = [];
var counts = [];

calculate(["a", "b"]);
calculate(["a", "c"]);

function calculate(result) {
    for (var i = 0; i < result.length; i++) {
        var check = 0;
        for (var j = 0; j < words.length; j++) {
            if (result[i] == words[j]) {
                check = 1;
                ++counts[j];
            }
        }
        if (check == 0) {
            words.push(result[i]);
            counts.push(1);
        }
        check = 0;
    }
}

Jsbin: http://jsbin.com/hawaco/2/edit?js,console

我所做的更改:

  • 将数组文字更改为提供字符串而不是变量名:[a,b] 更改为 ["a","b"]
  • 替换了tags(可能是旧名称)的实例,改用words
  • 将20秒更改为1秒
  • 使counts[j]的增量更清晰
  • 修复了i/j索引的使用

需要考虑的事情:

  • 也许将其作为字典而不是一对数组:{"a":1, "b":2},这将使代码更简单
  • 传递数组名称以允许其他累加器,或将方法和数组合并为单个对象

简化版:

var seen = {};

count(["a", "b"], seen);
count(["a", "c"], seen);

function count(words, accumulator) {
    for (var i = 0; i < words.length; ++i) {
        if(!accumulator.hasOwnProperty(words[i])) {
          accumulator[words[i]] = 1;
        } else {
          ++accumulator[words[i]];
        }
    }
}

结果:

>> seen
[object Object] {
  a: 2,
  b: 1,
  c: 1
}

JSBin:{{link1:http://jsbin.com/halak/1/edit?js,console}}

(JSBin是一个在线的HTML/CSS/JavaScript编辑器,您可以在其中编写和调试代码。以上链接将带您进入一个特定的JSBin示例,其中包含JavaScript和控制台输出。)

1
请检查以下内容: 您可以在此处进行测试:http://jsfiddle.net/knqz6ftw/
var words = [];
var counts = [];

calculate(['a', 'b']);
calculate(['a', 'c']);
calculate(['a', 'b', 'c']);

function calculate(inputs) {
    for (var i = 0; i < inputs.length; i++) {
    var isExist = false;
    for (var j = 0; j < words.length; j++) {
        if (inputs[i] == words[j]) {
            isExist = true
            counts[i] = counts[i] + 1;
        }
    }
    if (!isExist) {
        words.push(inputs[i]);
        counts.push(1);
    }
    isExist = false;
}
}

console.log(words);
console.log(counts);

输出为:
["a", "b", "c"] (index):46
[3, 2, 2] 

1
这是我的解决方案(使用一个对象):

  const checkWord = (str) => {
    let collection = {};
    // split the string into an array
    let words = str.split(' ');
    words.forEach((word) => {
     collection[word] = word;
   });
   // loop again to check against the array and assign a count
   for (let j = 0; j < words.length; j++) {
     if (words[j] === collection[words[j]]) {
       collection[words[j]] = 0;
     }
     collection[words[j]]++
   }
   console.log(collection);
 };

您可以使用 reduce

  const checkWord = (str) => {
  let collection = {};
  let words = str.split(' ');
  words.forEach((word) => {
     collection[word] = word;
   });
  for (var i = 0; i < words.length; i++) {
    if (words[i] === collection[words[i]]) {
      collection[words[i]] = 0;
    }
  }
  let total = words.reduce((occurrences, word) => {
    collection[word]++
    return collection;
}, 0);
    console.log(total);
  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接