而不是JavaScript的array_count_values [英] array_count_values for JavaScript instead
问题描述
我有以下PHP脚本,现在我需要在JavaScript中做同样的事情。 JavaScript中的函数是否与PHP函数类似,我一直在搜索但找不到类似的东西?我想要做的是计算某个单词在数组中使用的次数。
I have the following PHP-script, now I need to do the same thing in JavaScript. Is there a function in JavaScript that works similar to the PHP function, I have been searching for days but cannot find anything similar? What I want to do is to count the number of times a certain word is beeing used in an array.
$interfaceA = array($interfaceA_1,$interfaceA_2,$interfaceA_3,$interfaceA_4,$interfaceA_5,$interfaceA_6,$interfaceA_7,$interfaceA_8);
$interfaceA_array=array_count_values($interfaceA);
$knappsatsA = $interfaceA_array[gui_knappsats];
$touchpanelA = $interfaceA_array[gui_touchpanel];
推荐答案
为什么不简单地创建一个新的javascript数组计数
迭代原始数组,并增加数组中遇到的键的计数计数。
http://jsfiddle.net/4t28P/1/
Why not simply create a new javascript array "counts" Iterate over original array, and increament the count of "counts" for keys encountered in the array. http://jsfiddle.net/4t28P/1/
var myCurrentArray = new Array("apple","banana","apple","orange","banana","apple");
var counts = {};
for(var i=0;i< myCurrentArray.length;i++)
{
var key = myCurrentArray[i];
counts[key] = (counts[key])? counts[key] + 1 : 1 ;
}
alert(counts['apple']);
alert(counts['banana']);
这篇关于而不是JavaScript的array_count_values的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!