总结一个javascript数组字符串 [英] Summarizing a javascript array of strings

查看:79
本文介绍了总结一个javascript数组字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变长度的字符串数组,其中包含地牢和龙类名称。一个例子如下:

  var class_names = new Array(Wizard,Wizard,Wizard,巫师,
魔法师,终极魔法师);

在我的HTML中,我使用javascript window.onload 函数来设置javascript文件中的各种变量,以构建本地显示的页面内容。



对于名称这样的事情来说,这很简单:

  document.getElementById('charname')。innerHTML = name [0]; 

但是对于班级信息,我不想只抽出一大堆类名,我想让它浓缩下来。使用上面的例子'class_names',我想最终得到一个如下所示的字符串:

Wizard 3,Sorcerer 2,Ultimate Magus 1



即每个类名后面的数字应该是在数组中找到的重复次数。



任何人都有一个想法如何使这个动态发生,所以当我改变javascript文件将更多的类数据添加到class_names中,它会在我的HTML页面中正确显示?



感谢您提供任何有关此宠物项目的帮助(即创建我的广告系列中每个角色的HTML页面都可以作为角色表格打印出来......这比为每个角色手动书写页面或在香草纸上手写书写页面好得多)。

解决方案

很简单,只需循环访问数组并重复计数即可。

  var l = class_names.length,i,tmp = {},ret = []; (i = 0; i< l; i ++){
if(!tmp [class_names [i]])tmp [class_names [i]] = 0;
tmp [class_names [i]] ++; (tmp){
if(tmp.hasOwnProperty(i)){
ret.push(i ++ tmp [i]);
}

}
}
//输出是ret.join(,);


I have a variable length array of strings declared in javascript that contains Dungeons and Dragons class names. An example of this is below:

var class_names = new Array("Wizard", "Wizard", "Wizard", "Sorcerer", 
    "Sorcerer", "Ultimate Magus");

In my HTML, I use the javascript window.onload function to set a variety of variables from the javascript file to build the content of the page being displayed locally.

For things like name, this is easy:

document.getElementById('charname').innerHTML = name[0];

But for the class info, I don't want to just pump out a massive string of class names, I want it condensed down. Using the example 'class_names' above, I want to end up with a string that looks like this:

"Wizard 3, Sorcerer 2, Ultimate Magus 1"

i.e. the number after each class name should be the number of repetitions found in the array.

Anyone have an idea how to make this happen on the fly, so when I alter the javascript file to add more class data to class_names, it is displayed appropriately on my HTML page?

Thanks in advance for any help I get on this pet project (namely creating a HTML page for each character in my campaign that can be printed out as a character sheet....it's far better than manually writing a page for each character, or handwriting it on vanilla sheets).

解决方案

It's easy enough, just loop through the array and count repetitions.

var l = class_names.length, i, tmp = {}, ret = [];
for( i=0; i<l; i++) {
    if( !tmp[class_names[i]]) tmp[class_names[i]] = 0;
    tmp[class_names[i]]++;
}
for( i in tmp) {
    if( tmp.hasOwnProperty(i)) {
        ret.push(i+" "+tmp[i]);
    }
}
// output is ret.join(", ");

这篇关于总结一个javascript数组字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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