我有一个数组:
var locations = ['Afghanistan','Albania','Algeria','New York'];
和一个字符串:
var string = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
我想计算数组中每个关键字在字符串中出现的次数,但找不到最佳方法。
最佳答案
这是我的版本:
function countItems(a, s) {
var x, i, output = {};
for (x = 0; x < a.length; x++) {
i = 0;
output[a[x]] = 0;
while ((i = s.indexOf(a[x], i)) > -1) {
output[a[x]]++;
i++
}
}
return output;
}
var result = countItems(locations, string);
// result['Albania'] === 0
试一试 here .
关于javascript - 从javascript中的关键字数组计算字符串中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1400235/