为什么这个 javascript 代码没有通过,而另一个却通过了,如果它们生成相同的输出。 (减少 vs 为)

why this javascript code don't pass but the other one does, if they generate the same output. (reduce vs for)

我正在使用 adventJS challenge #2:

You have received a letter ✉️ with all the gifts you must prepare. The issue is that it is a string of text and is very difficult to read . Fortunately they have separated each gift by a space! (although be careful, because being children, they might have inserted more spaces than needed)

What's more, we have noticed that some words come with a _ in front of the word, for example _playstation, which means that it is striked out and should not be counted.

Transform the text to an object that contains the name of each gift and the times it appears. For example, if we have the text:

const carta = 'bici coche balón _playstation bici coche peluche'

running the method should return the following:

const regalos = listGifts(carta)

console.log(regalos)
/*
{
  bici: 2,
  coche: 2,
  balón: 1,
  peluche: 1
}
*/

Keep in mind that the tests can be more exhaustive... Beware of counting empty spaces!

我的代码没有通过测试,但它应该可以工作:

const carta = 'bici coche balón _playstation bici     coche peluche'

function listGifts(letter) {
  rta = letter.split(/\s+/).reduce(function(acc,value){
    const g = acc[value]
    if(!g){
      if(!value.includes("_")){
        acc[value]=1
      }
    }else{
      acc[value]=g+1
    }
    return acc
  },{});
  return rta;
}

console.log(listGifts(carta))

但是这段代码通过了:

const carta = 'bici coche balón _playstation bici     coche peluche'

function listGifts2(letter) {

    let palabras = letter.split(" ")
    let lista = {};
    
    for(let i = 0; i < palabras.length; i++){
        if (!palabras[i].includes("_")){
            if(lista[palabras[i]]==undefined){
                lista[palabras[i]] = 1
            } else {
                lista[palabras[i]] += 1
            }
        }
    }
    delete lista[""]
    return lista
}

console.log(listGifts2(carta))

我不明白。我使用相同的条件,相同的数据类型。 即使我更改正则表达式以与正确的代码一致,它仍然不起作用:

const carta = 'bici coche balón _playstation bici     coche peluche'

function listGifts(letter) {
  const carta = letter.split(" ")
  
  rta = carta.reduce(function(acc,value){
    const g = acc[value]
    if(!g){
      if(!value.includes("_")){
        acc[value]=1
      }
    }else{
      acc[value]=g+1
    }
    return acc
  },{});
  delete rta[""]
  return rta;
}

console.log(listGifts(carta))

主要区别在于第一个版本可能 return 一个具有空字符串的对象 属性:

{ "": 1 }

当输入字符串以 space 开头或以 space 结尾或者是空字符串时,会发生这种情况。

因此,要么在您的第一个版本中也包括该 delete 操作,要么使用任何其他方式来避免空字符串在您的最终对象中显示为 属性。

注意:描述中说当一个词开头时下划线应该被忽略。这意味着 a_b 不应被排除在外。所以你不应该使用 includes 但测试第一个字符不是下划线。