编写一个接收字符串并返回每个字符串计数的函数

时间:2019-07-26 18:00:19

标签: javascript

我实际上只能解决这个简单的问题。无论如何,我找到了另一种方法来解决此问题,但我无法通过代码来解决问题。

function charCout(str)
{
    str = str.toLowerCase();
    var f  = {};

    for(let i =0;i<str.length;i++)
    {
        if(str[i] === " ")
        {
            continue;
        }
        else{
            if(str[i] in Object.keys(f))
            {
                f[str[i]] += 1;
            }
            else
            {
                f[str[i]] = 1;
            }
        }
    }
  return(f);   
}




input: charCout("my name is Khan23")
expected output: {2: 1,3: 1,a: 2,e: 1,h: 1,i: 1,k: 1,m: 2,n: 2,s: 1,y: 1}
what i got: {2: NaN,3: NaN,a: 1,e: 1,h: 1,i: 1,k: 1,m: 1,n: 1,s: 1,y: 1}

6 个答案:

答案 0 :(得分:1)

只需查看强制属性是否存在,例如:#include <iostream> #include <string> using namespace std; int main() { string str1ok = "Im a string"; string str2ok = "Im a string"; string str3ok = "Im a string different"; //First condition with and operator (&&) you can compare with a lot && operators if(str1ok.compare(str2ok) == 0 && str3ok.compare(str2ok) == 0){ //First condition is true, second false, this condition is false because have true and false, need have true and true for be true cout << "1st condition" << endl; } //Another condition with or operator (||) one condition need be true, if not is false if(str1ok.compare(str2ok) == 0 || str3ok.compare(str2ok) == 0){ //First condition is true, only for this this condition is true, second condition is false. cout << "2nd condition" << endl; } //You can make a mixed the operators like this some condition && (anothercondition || condition) return 0; }

if(f[str[i]])

答案 1 :(得分:0)

您使用错误的方式来检查密钥是否在对象中。

您可以使用if-else运算符将||压缩为一行。

f[str[i]] = f[str[i]] + 1 || 1 

它检查f[str[i]]是否已经存在。如果str[i]不是f的键,则f[str[i]]将返回undefined,而undefined + 1将是NaN

NaN是一个伪造的值,因此NaN || 1的取值为1

如果f[str[i]]存在,则它将返回大于0的任何数字,因此它将被设置为f[str[i]] + 1(递增1)

function charCount(str)
{
    str = str.toLowerCase();
    var f  = {};

    for(let i =0;i<str.length;i++)
    {
        if(str[i] !== " ")
        {
            f[str[i]] = f[str[i]] + 1 || 1 
        }
    }
  return(f);   
}
console.log(charCount("my name is Khan23"))

说明:

您也可以使用reduce()

const charCount = str => str
                          .split(' ')
                          .join('')
                          .split('')
                          .reduce((ac,a) => 
                              (ac[a] = ac[a] + 1 || 1, ac), 
                          {})


console.log(charCount("my name is Khan23"))

答案 2 :(得分:0)

您可以使用str.split("")获取字符列表,然后执行类似的操作

const splitted = str.split("");
const resut = {};
splitted.map(letter => result[letter] ? result[letter] = 1 :  result[letter] ++)

这只是个主意

答案 3 :(得分:0)

使用Object.keys(f).includes(str[i])代替str[i] in Object.keys(f)是解决方案

in运算符主要用于检查Object是否提供特定属性

inArray.prototype.includes上的Mozilla文档将有所帮助。

按照您的功能进行修改

function charCout(str)
{
    str = str.toLowerCase();
    var f  = {};

    for(let i =0;i<str.length;i++)
    {
        if(str[i] === " ")
        {
            continue;
        }
        else{
            if(Object.keys(f).includes(str[i]))
            {
                f[str[i]] += 1;
            }
            else
            {
                f[str[i]] = 1;
            }
        }
    }
  return(f);   
}

答案 4 :(得分:0)

您可以利用String.protoype.splitArray.prototype.reduce来解决此问题。查看代码中的注释以获取详细信息:

const charCount = s => {
  //Create an array of characters found in the string (filtering out spaces)
  const chars = s.split('').filter(char => char.trim());

  //Use reduce to create an occurrence map - increment by 1 each time a character is encountered
  return chars.reduce((accum, char) => {
    accum[char] = accum[char] ? accum[char] + 1 : 1;
    return accum;
  }, {});
};

console.log(charCount("my name is Khan23"))

答案 5 :(得分:0)

谢谢大家的有益建议。我终于发现我的代码出了什么问题。

我的缺陷代码的输入和输出如下:

输入:charCout(“我的名字是Khan23”)

预期输出:{2:1,3:1,a:2,e:1,h:1,i:1,k:1,m:2,n:2,s:1,y:1 }

我得到了什么:{2:NaN,3:NaN,a:1,e:1,h:1,i:1,k:1,m:1,n:1,s:1,y: 1};

我使用“ in”运算符来查找Object.keys(f)数组是否存在特定的字符串值。那正是我出错的地方。

在引用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in之后,我知道“ in”不能用于使用索引值对数组进行过滤。

相关问题