【发布时间】:2023-03-10 23:26:01
【问题描述】:
我有一个函数,它将字符串的结果生成到一个对象中,其中字母被视为键/值格式的属性值。
var output = countAllCharsIntoObject('banana');
console.log(output); // --> {b: 1, a: 3, n: 2}
我的问题是除了字符串数组的循环
function countAllCharsIntoObject(str){
var arr = str.split('');
var obj = {};
for(var i = 0; i < arr.length; i++) {
//how to iterate the arr[i] and assign the value of the chars to the
//keys/values of the new obj. And if more then 1 indexOf(arr[i]) then
//change through an iteration the value of the new char key.I tried so
//many solutions without effect.
}
return obj;
}
我无法理解这样一个事实,即我同时在一个循环内循环,并分配给循环结果的键/值(动态递增值)。 任何帮助,将不胜感激! 请用纯 JS... 没有下划线或 lodash 或 jQuery 解决方案。 谢谢!
【问题讨论】:
-
循环体:
obj[arr[i]]=obj[arr[i]]||0;obj[arr[i]]++; -
谢谢!似乎是一个很好的指针......让我看看......
标签: javascript object count chars