我期待从我的字符串进行的计数输出创建一个数组

时间:2016-06-22 14:46:29

标签: javascript html

我正在尝试制作我的下面的JS代码,Develop和Array of 每个元音的数量 1)A的数量 2)E的数量 3)我的数量 4)数为0 5)U的计数

读取字符串代码后,生成每个元音发生的次数。 但是现在我需要创建一个显示的元素,元音发生频率最高

我知道这与为

创建变量有关

var largestSoFar等......但如何将它拼凑在一起我遇到了问题。

/ *  *要更改此模板,请选择“工具”|模板  *并在编辑器中打开模板。  * /

"indexHtmlPath": "../../iris_app.war/WEB-INF/views/jsp/app/index.jsp",
"output": {
  "base": "${workspace.build.dir}/${build.environment}/${app.name}",
  "page": {
    "path": "index.jsp",
    "enable": true
  },
  "manifest": "${build.id}.json",
  "js": "${build.id}/app.js",
  "appCache": {
    "enable": false
  },
  "resources": {
    "path": "${build.id}/resources",
    "shared": "resources"
  }
},

3 个答案:

答案 0 :(得分:0)

为什么不是这样的?您提供string,它会返回一个object,其中包含每个元音的计数?

function countVowels(str) {

    var result = {};
    result.a = 0;
    result.e = 0;
    result.i = 0;
    result.o = 0;
    result.u = 0;

    for (var i = 0, len = str.length; i < len; i++) {
        switch(str[i].toLowerCase()) {
            case "a":
                result.a = result.a + 1;
                break;
            case "e":
                result.e = result.e + 1;
                break;
            case "i":
                result.i = result.i + 1;
                break;
            case "o":
                result.o = result.o + 1;
                break;
            case "u":
                result.u = result.u + 1;
                break;
            default:
                break;
        }
    }

    return result;
}

当你得到结果object时,你可以进行检查,看看哪个是最多的。

答案 1 :(得分:0)

另一种方法可能就像

&#13;
&#13;
var str = "When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters. If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.",
 vowels = {"a":0,"e":0,"i":0,"o":0,"u":0},
     ok = Object.keys(vowels);
 maxvow = "";
for (var i = 0, len = str.length; i < len; i++ ){
  var chr = str[i].toLowerCase();
  chr in vowels && ++vowels[chr]; // or ok.includes(chr) && ++vowels[chr];
}
maxvow = ok.reduce((p,k) => vowels[k] > p[0] ? [vowels[k],k] : p,[0,""])[1];
console.log(vowels);
console.log(maxvow);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以分割字符串并使用一个对象来计算元音和其他字母。

var count = { a: 0, e: 0, i: 0, o: 0, u: 0, other: 0 },
    test = 'Es war einmal ein schwarzes Kaninchen';

test.toLowerCase().split(/(?=[a-z])/).forEach(function (c, i) {
    if (c[0] in count) {
        count[c[0]]++;
    } else {
        count.other++;
    }
});

console.log(count);