简体   繁体   English

我需要帮助理解几行代码

[英]I need help understanding a couple lines of code

can someone help me understand what is happening on this line:有人可以帮助我了解这条线上发生了什么:

chars[char] = (chars[char] || 0) + 1;

and on line:并在线:

.filter((char) => char[1] > 1).map((char) => char[0]);
/* FULL CODE */
const getRepeatedChars = (str) => {
  const chars = {};
  for (const char of str) {
    chars[char] = (chars[char] || 0) + 1;
  }
  return Object.entries(chars)
    .filter((char) => char[1] > 1)
    .map((char) => char[0]);
};

console.log(getRepeatedChars("aabbkdndiccoekdczufnrz"));
chars[char] = (chars[char] || 0) + 1;

This adds 1 to the value of chars[char] .这会将chars[char]的值加1 If there's no element in the object with key char , the value of chars[char] will be undefined.如果 object 中没有键为char的元素,则chars[char]的值将是未定义的。 undefined || 0 undefined || 0 is 0 ; undefined || 00 ; adding 1 to this initializes the element to 1 the first time a particular character is encountered.第一次遇到特定字符时,将此元素加1会将元素初始化为1

Object.entries(chars)
.filter((char) => char[1] > 1).map((char) => char[0]);

Object.entries(chars) returns an array whose elements are nested arrays of the form [key, value] , the keys and values of the chars object. Object.entries(chars)返回一个数组,其元素嵌套为[key, value]形式的 arrays , chars ZA8CFDE6331BD59EB2AC96F8911C4B6666 的键和值。 The keys are the characters in the strings, the values are the repetition counts.键是字符串中的字符,值是重复计数。 So char[1] > 1 tests if the character appeared more than once, and filter() returns an array where this is true.所以char[1] > 1测试字符是否出现了不止一次,并且filter()返回一个数组,其中为真。 Then .map() returns char[0] , which is the character.然后.map()返回char[0] ,即字符。 So this returns the characters that appeared more than once.所以这会返回多次出现的字符。

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

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