【问题标题】:How can I shortened this?我怎样才能缩短这个?
【发布时间】:2013-10-30 19:21:15
【问题描述】:

我正在尝试自学编程并从 javascript 开始。要了解更多信息,我一直在完成练习挑战,其中一个挑战是编写一个脚本,该脚本将确定字符串中重复字母最多的单词的第一种情况。我能够用我制作的这段代码完成它:

string = "Hey i believe";
string = string.split(" ");
stringarray = [];
longestlength = 0; 

for (i = 0; i < string.length; i++) {
    stringarray.push(0);
}

for (i = 0; i < string.length; i++) {
    if (string[i].length > longestlength) {
        longestlength = string[i].length;
        longestword = string[i];
    }
}

for (x = 0; x < string.length; x++) {
    y = 0;
    z = 0;
    while (z < string[x].length) {
        if (string[x].substr(z,1) == string[x].substr(y,1) && z !== y) {
            stringarray[x] += 1;
            y = string[x].length -1;
        }
        y++;
        if (y == string[x].length) {
            z++;
            y = z;
        }
    }
}

if (Math.max.apply(null,stringarray) === 0) {
    mostrptltword = -1;
}
else {
    mostrptltword = string[stringarray.indexOf(Math.max.apply(null,stringarray))];
}

console.log(mostrptltword);

但是要在挑战中获得所有可能的分数,它必须在 10 分钟内完成,这花了我 25 分钟。所以我的问题是我是否把事情复杂化了?导致我编写比需要更长的脚本?我已经阅读了一些关于正则表达式之类的内容,以及它们如何真正缩短脚本长度以及编写它们所需的时间,或者可能是另一种比我必须制作的所有循环更有用的技术?

【问题讨论】:

  • 如果代码按原样运行良好,并且您只是在寻找更简洁的编写方法,则应该将其移至codereview.stackexchange.com
  • 考虑到您从未真正使用过longestlength 和longestword 的最终值,您可以摆脱那个循环和那些变量。
  • 无论如何,“最重复的字母”是什么意思,我可以从周日开始解释这 10 种方式。

标签: javascript for-loop while-loop


【解决方案1】:
var words = "Heyyyyy I believe".split(' '); // split the words into an array


var values = [],   // total of times that a letter appears
    k = 0,         // 'global' counter. I'm using this to iterate over the values array
    heigher = 0,   // holds de heigher occurrence of a letter 
    letter = "";   // the letter that most appears in that word
    word = "";     // the word


// iterate over all the words
for(var i = 0; i < words.length; i++) {  

    // iterate over each letter in each word
    for(var j = 0; j < words[i].length; j++) {

        // holds the occurrence time
        // RegEx: get the word in the position 'i' and check how many times the letter appears on the position [j] appears
        values[k] = words[i].match(new RegExp(words[i][j],'g')).length;

        // check if the next letter appears more times than the previous one
        if(values[k] > heigher) {
            // hold the values of interest
            heigher = values[k];
            letter = words[i][j];
            word = words[i];
        }
        k++;
    } 
}

console.log("word: " + word + " letter: " + letter + " total: " + heigher);

jsfiddle:http://jsfiddle.net/felipemiosso/FyCHG/

已评论。希望对你有帮助:)

【讨论】:

  • 哦,哇,这确实有很大帮助!它让我更好地理解了 RegExp 的用处。
猜你喜欢
  • 2015-03-13
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2022-01-04
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多