计算字符串中的唯一单词 [英] Counting unique words in strings

查看:114
本文介绍了计算字符串中的唯一单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我尝试将字符串数组提供给向单词数组添加唯一单词的函数,并且如果单词已经在数组中以增加count数组中相应元素的计数:

Below I am trying to give string arrays to a function that adds unique words to a words array, and if the word is already in the array to increase the count of the corresponding element in the count array:

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

words = a, b count = 2, 1

当我期望是:字= a,b,c计数= 2,1,1

When I expect it to be: words = a,b,c count = 2,1,1

非常感谢您提前提供帮助

Thanks for any help in advance

推荐答案

请检查以下内容:您可以在以下网站上进行测试: http://jsfiddle.net/knqz6ftw/

Please check this : you can test it on : 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] 

这篇关于计算字符串中的唯一单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆