简体   繁体   English

我需要找到字符串 js 中两个字符之间的距离。 我有一个解决方案,但我无法理解与 if 语句相关的代码片段

[英]i need to find the distance between two characters in string js. i have a solution but i can't understand the snippet of code related to if statement

The task was to write a function subLength() that takes 2 parameters, a string and a single character.任务是编写一个 function subLength(),它接受 2 个参数,一个字符串和一个字符。 The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. function 应该在字符串中搜索该字符的两次出现,并返回它们之间的长度,包括这 2 个字符。 If there are less than 2 or more than 2 occurrences of the character the function should return 0.如果该字符出现少于 2 次或超过 2 次,则 function 应返回 0。

const subLength = (str, char) => {
let charCount = 0;
let len = -1;

for (let i=0; i<str.length; i++) {
  if (str[i] == char) {
    charCount++;
    if (charCount > 2) {
      return 0;
    }
// could somebody explain why -1 is equal to len and then len is reassigned to i???       
if (len == -1) {
      len = i;
    } else {
      len = i - len + 1
    }
  }
}
if (charCount < 2) {
  return 0;
}

return len;
};

dude there are other ways to do this.伙计,还有其他方法可以做到这一点。 see if my code helps you to understand any better:)看看我的代码是否可以帮助您更好地理解:)

const subLength = (str, char) => {
  let charCount = 0;
  let letterFound = [];
  let arr = str.split('');
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === char) {
      letterFound.push(i);
      charCount++;
    }
  }
  let result = arr.slice(letterFound[0], letterFound[1]).length + 1;
  if (charCount > 2 || charCount < 2) return 0;
  return result;
}
console.log(subLength('saturday', 'a'));

in the first occurrence len= -1 so: (len ==-1) turned to true;在第一次出现 len= -1 所以: (len ==-1) 变为 true; and len is changed to i so len=i;并且 len 更改为 i 所以 len=i; in the second occurance len is not -1 so:在第二次出现 len 不是 -1 所以:

len = i - len -1;

in essence, in the above expression, len keeps the index of the first occurrence, and i has the index of second occurrence, so the difference will be, the difference between two occurrences, 'qweraq' : first occurrance: 0, second: 6. 6-0-1= 5 is difference;本质上,在上面的表达式中, len 保持第一次出现的索引,而 i 有第二次出现的索引,所以区别将是,两次出现之间的差异,'qweraq':第一次出现:0,第二次:6 . 6-0-1= 5 是差值;

This is how I manage to rewrite your code.这就是我设法重写您的代码的方式。 Hope this helps.希望这可以帮助。

 const subLength = (str, char) => { const arr = str.split(''); let count = 0; arr.forEach(letter => letter === char ? count++ : '') const result = arr.some(letter => { if (arr.indexOf(char) !== arr.lastIndexOf(char) && count == 2) { return true } return false }) return result ? Math.abs(arr.indexOf(char) - arr.lastIndexOf(char)) + 1 : 0 }

Whilst its possible to calculate the indexes and the count within a single loop, given the triviality I'd favor standard API methods for scanning.虽然可以在单个循环中计算索引和计数,但考虑到琐碎性,我倾向于使用标准 API 方法进行扫描。 one could always optimize later if the application actually called for it.如果应用程序确实需要它,那么以后总是可以优化。

First we convert the string to an array so that we have the ability to filter for matches to the input character, and derive the length.首先,我们将字符串转换为数组,以便我们能够过滤与输入字符匹配的内容,并得出长度。

Only if there are 2 occurrences do we calculate the distance between using the indexOf and lastIndexOf methods on string (note that these will only require a second full scan of the string if the two occurrences are consecutive).仅当出现 2 次时,我们才计算在字符串上使用indexOflastIndexOf方法之间的距离(请注意,如果两次出现是连续的,则只需要对字符串进行第二次完整扫描)。

Otherwise, the result should be 0.否则,结果应为 0。

 const subLength = (str, chr) => { const count = str.split('').filter(ltr => ltr === chr).length if (count === 2) { return (str.lastIndexOf(chr) - str.indexOf(chr)) + 1 } return 0 } console.log(subLength('asddfghvcba', 'a')) console.log(subLength('asddfghvcba', 'x')) console.log(subLength('aaaaaaaaaaa', 'a'))

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

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