从javascript中的关键字数组计算字符串中的出现次数 [英] Count occurances in string from keyword array in javascript

查看:141
本文介绍了从javascript中的关键字数组计算字符串中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

var locations = ['Afghanistan','Albania','Algeria','New York'];

和一个字符串:

var string = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';

我想计算数组中每个关键字出现在字符串中的次数,找出最好的方法。

I want to count the number of times each keyword in the array appears in the string but can't figure out the best way to do that.

推荐答案

这是我的版本:

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

尝试此处

这篇关于从javascript中的关键字数组计算字符串中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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