计算字符串中的唯一单词

时间:2014-09-01 09:06:56

标签: javascript arrays

下面我尝试将字符串数组赋予一个向单词数组添加唯一单词的函数,如果该单词已经在数组中以增加计数数组中相应元素的计数:

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;
    }
}

然而输出结果如下:

words = a,b count = 2,1,

当我期望它是: words = a,b,c count = 2,1,1

感谢您提前提供任何帮助

4 个答案:

答案 0 :(得分: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>

输出:

  

[&#34; a&#34;,&#34; b&#34;,&#34; c&#34;]
  []
    a 2
    b 1
    c 1

答案 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(可能是旧名称)的实例
  • 将20s更改为1s
  • 使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:http://jsbin.com/halak/1/edit?js,console

答案 2 :(得分: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] 

答案 3 :(得分: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);
  };