简体   繁体   English

查找数组中的重复字母(javascript)

[英]Find repeated letters in an array (javascript)

I'm new on this and javascript. 我是这个和javascript的新手。 I've tried to solve an exercise that consist to find repeated letter a in an array. 我试图解决一个包含在数组中找到重复字母a的练习。 The way to do is use basic structures (no regex neither newer ways of javascript (only ES5)). 要做的方法是使用基本结构(没有正则表达式,也没有较新的javascript方法(仅ES5))。 I need to do it this way to understand the bases of the language. 我需要通过这种方式来理解语言的基础。

The output must be this: 输出必须是这样的:


//Captain America, the letter 'C' => 2 times. //美国队长,字母“ C” => 2次。
//Captain America, the letter 'A' => 4 times. //美国队长,字母“ A” => 4次。
//Captain America, the letter 'I' => 2 times. //美国队长,字母“ I” => 2次。

I'm not looking for the solution, only the way to do it and its logical structures. 我不是在寻找解决方案,而只是在寻找解决方案及其逻辑结构。 Any suggestions are welcome. 欢迎任何建议。

My way but it doesn't work: 我的方式,但是不起作用:

function duplicateLetter(name) {
  var newArray = [];

  for (var i=0; i<name.length; i++) {
    console.log(name[i].indexOf(newArray));

    if (name[i].indexOf(newArray) === 0) {
        newArray.push(name[i]);
    }
  }

   console.log(newArray);   

  //console.log(name + ", the letter '" + (newArray[0]).toUpperCase() + "' => " + newArray.length + " times");
}

duplicateLetter("Captain America");
function duplicateLetter(o) {
    var arr = o.toUpperCase().split('');
    var obj = {};

    for(var v in arr) {
        obj[arr[v]] = obj[arr[v]] || 0;
        obj[arr[v]]++;
    }

    for(var v in obj) {
        console.log(o + ", the letter '" + v + "' => " + obj[v] + ' times.');
    }
}

duplicateLetter("Captain America");

The explanation: 说明:

  • We make the string upper case, then turn it into an array of letters. 我们将字符串大写,然后将其转换为字母数组。
  • We loop over the array, here, arr[v] becomes our letter, and: 我们遍历数组,在这里, arr[v]成为我们的字母,并且:
    • If the key arr[v] doesn't exist in our object, we set it to 0 . 如果键arr[v]在我们的对象中不存在,则将其设置为0
    • We increment the value of the key arr[v] in our object (this causes obj['c'] to increment every time our letter is c. You can notice that this keeps track of the number of letters in our string. 我们增加对象中键arr[v]的值(这会使obj ['c']每当我们的字母为c时都会增加。您会注意到,它跟踪了字符串中的字母数。
  • We loop over the object v, printing the number of occurrences of each letter to console. 我们遍历对象v,将每个字母的出现次数打印到控制台。

Note that this considers the space character as a letter. 请注意,这会将空格字符视为字母。 If you want an answer that doesn't, please specify so. 如果您想要的答案不正确,请指定。

Here's a different answer that doesn't use objects and only counts letters (and not spaces or punctuation) to prove that everything is possible in more than one way. 这是一个不使用对象的答案,它仅使用字母(而不是空格或标点符号)来证明一切都是以一种以上的方式实现的。

// Not using objects and not counting anything but letters.
function duplicateLetter(o) {
    var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var arr = o.toUpperCase().split('');
    var count = [];

    for(var v in arr) {
        pos = letters.indexOf(arr[v]);
        if(pos < 0) continue; // It wasn't a letter.
        count[pos] = count[pos] || 0;
        count[pos]++;
    }

    for(var v in count) {
        if(!(count[v] > 0)) continue; // The letter never appeared.
        console.log(o + ", the letter '" + letters[v] + "' => " + count[v] + ' times.');
    }
}

duplicateLetter("Captain America");

I could probably also attempt an answer that doesn't use arrays at all! 我可能还会尝试一个根本不使用数组的答案!

Edit: You can use for(a in b) loops to iterate arrays as well as objects. 编辑:您可以使用for(a in b)循环来迭代数组和对象。 This is because an array is really just an object in which all enumerable properties have integer indices: 这是因为数组实际上只是一个对象,其中所有可枚举的属性都具有整数索引:

arr = [10,15,"hi"] is almost the same as arr = {'0' : 10, '1' : 15, '2' : "hi"} in the way Javascript works internally. arr = [10,15,"hi"]与JavaScript内部工作方式几乎arr = {'0' : 10, '1' : 15, '2' : "hi"} Therefore, for (v in arr) will iterate over the array normally. 因此,for(v in arr)将正常遍历数组。

As requested, the same answer with normal for loops: 根据要求,与普通for循环的答案相同:

// Not using objects and not counting anything but letters.
function duplicateLetter(o) {
    var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var arr = o.toUpperCase().split('');
    var count = [];

    for(var v = 0; v < arr.length; v++) {
        pos = letters.indexOf(arr[v]);
        if(pos < 0) continue; // It wasn't a letter.
        count[pos] = count[pos] || 0;
        count[pos]++;
    }

    for(var v = 0; v < count.length; v++) {
        if(!(count[v] > 0)) continue; // The letter never appeared.
        console.log(o + ", the letter '" + letters[v] + "' => " + count[v] + ' times.');
    }
}

duplicateLetter("Captain America");

Note that nothing changed outside what was in the for brackets. 请注意,在for括号中, 什么都没有改变 The for-in notation is just easier for the human brain to comprehend, in my opinion, and is the reason I used it. 在我看来,for-in标记对于人脑来说更容易理解,这就是我使用它的原因。

As for count[pos] = count[pos] || 0; 至于count[pos] = count[pos] || 0; count[pos] = count[pos] || 0; , explaining why it works the way it does is extremely tedious, since it requires that you know precisely what the || ,解释它为什么如此工作是非常繁琐的,因为它要求您确切地知道||是什么。 operator does. 操作员可以。 So I'm just going to state what it does, without explaining it. 因此,我将仅说明它的功能,而无需解释。

Basically, count[pos] = count[pos] || 0; 基本上, count[pos] = count[pos] || 0; count[pos] = count[pos] || 0; is the same as: 是相同的:

if(count[pos]) { // If count[pos] evaluates to true.
    count[pos] = count[pos]
} else { // count[pos] is false, '', null, undefined, 0, or any other value that evaluates to false.
    count[pos] = 0;
}

Note that this works because at the start, count[pos] is undefined ( count is an empty array), so it puts a 0 in it. 请注意,这样做之所以有效,是因为在开始时count[pos]undefinedcount是一个空数组),因此将0放入其中。 If we find the letter again, count[pos] is defined, and is a positive value, and therefore evaluates to true , so we don't change it. 如果我们再次找到字母,则count[pos]被定义并且为正值,因此其值为true ,因此我们不会对其进行更改。

Just consider a = a || b 只要考虑a = a || b a = a || b to be equal to: a = a || b等于:

Put the default value of b into a if a is undefined (or evaluates to false by any other means).` 如果a undefined (或通过其他任何方法求值为false ),则将b的默认值放入a

Make an object whose keys are the letters and values are the number of times that letter was repeated. 制作一个对象,其键是字母,值是该字母重复的次数。 For example, 'abbc' => {'a': 1, 'b': 2, 'c': 1} 例如,'abbc'=> {'a':1,'b':2,'c':1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM