简体   繁体   English

如何在javascript中的对象中动态添加属性?

[英]How to add properties dynamically in the object in javascript?

I want to know that how many times each alphabet comes in the 'input' variable. 我想知道每个字母多少次出现在“输入”变量中。 For this I am loop through each character and storing them in an object and also how many they appeared in the sentence. 为此,我要遍历每个字符并将它们存储在一个对象中,以及它们在句子中出现的数量。 But It is consoling NaN. 但这令人安慰。 Please show me where is the error? 请告诉我错误在哪里?

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;
    });
    console.log(object);
} 

You can use hasOwnProperty to check if a property exists. 您可以使用hasOwnProperty来检查属性是否存在。

 var input = "why this kolaveri kolaveri di"; var object = {}; input.replace(/\\s/g,"").split("").forEach(function(item){ // If the property doesn't exist, initialize it to 0 if (!object.hasOwnProperty(item)) object[item] = 0; object[item]++ }); console.log(object); 

For the haters, you can initialize to 1 and only increment in the else. 对于仇恨者,可以将其初始化为1,而只能在else中递增。 Essentially the same but a few cycles more efficient. 本质上相同,但效率提高了几个周期。 Use whichever you think looks best. 使用您认为最合适的方法。

  // If the property doesn't exist, initialize it to 1
  if (!object.hasOwnProperty(item))
    object[item] = 1;
  else
    object[item]++;

这项工作

  typeof object[item] == 'undefined' ?

You had the problem in the below line of code . 您在下面的代码行中遇到了问题。

object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;

Update Code: 更新代码:

 var input = "why this kolaveri kolaveri di"; function processData(input) { var object = {}; input.replace(/\\s/g,"").split("").forEach(function(item){ if(object[item] == null) { object[item] = 0; object[item]++; }else{ object[item]++; } }); console.log(object); } //testing here processData(input); 

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

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