gpt4 book ai didi

javascript - 从javascript中的关键字数组计算字符串中的出现次数

转载 作者:行者123 更新时间:2023-12-03 10:03:00 25 4
gpt4 key购买 nike

我有一个数组:

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/

25 4 0
文章推荐: python-2.7 - 如何使用广播从具有列表 2d 索引的 2D numpy 数组中获取元素?
文章推荐: powershell - 在搜索中过滤掉子 OU
文章推荐: unix - Ctrl-C 和 SIGINT 有什么区别?
文章推荐: javascript - 如何使整个
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com