[英]How to add properties dynamically to each object in an javascript array
[英]How to add properties dynamically in the object in javascript?
我想知道每个字母多少次出现在“输入”变量中。 为此,我要遍历每个字符并将它们存储在一个对象中,以及它们在句子中出现的数量。 但这令人安慰。 请告诉我错误在哪里?
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);
}
您可以使用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);
对于仇恨者,可以将其初始化为1,而只能在else中递增。 本质上相同,但效率提高了几个周期。 使用您认为最合适的方法。
// If the property doesn't exist, initialize it to 1
if (!object.hasOwnProperty(item))
object[item] = 1;
else
object[item]++;
这项工作
typeof object[item] == 'undefined' ?
您在下面的代码行中遇到了问题。
object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;
更新代码:
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.