算上字符串occurances从JavaScript的关键字数组 [英] Count occurances in string from keyword array in javascript

查看:200
本文介绍了算上字符串occurances从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

试试看这里

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

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