[英]Counting all characters in a string
I want to count all characters in a string and return it to an object.我想计算一个字符串中的所有字符并将其返回给一个对象。 I have tried but I'm unable to get the correct answer.我试过了,但我无法得到正确的答案。
This is my code:这是我的代码:
function countAllCharacters(str) { var a = str.split(""); var obj = {}; a.forEach(function(s){ var count=0; for(var j=0;j<a.length;j++){ if(s==a[j]){ count+=1; } obj[a[j]]=count; } }); return obj; } console.log(countAllCharacters('banana'));
Output:输出:
{ b: 0, a: 3, n: 2 }
Which obviously is wrong.这显然是错误的。
Can anyone help me with that?任何人都可以帮助我吗? Where I am going wrong?我哪里出错了?
The minimum necessary change is that obj[a[j]]=count;
最小的必要变化是obj[a[j]]=count;
should be obj[s]=count;
应该是obj[s]=count;
, because you have that line running on every iteration of the inner loop regardless of whether j
refers to the letter you're currently tallying. ,因为无论j
是否指您当前正在计算的字母,您都会在内循环的每次迭代中运行该行。
function countAllCharacters(str) { var a = str.split(""); var obj = {}; a.forEach(function(s){ var count=0; for(var j=0;j<a.length;j++){ if(s==a[j]){ count+=1; } obj[s]=count; } }); return obj; } console.log(countAllCharacters('banana'));
However, you don't need a nested loop.但是,您不需要嵌套循环。 Your outer .forEach()
can update the count for the current letter directly:您的外部.forEach()
可以直接更新当前字母的计数:
function countAllCharacters(str) { var a = str.split(""); var obj = {}; a.forEach(function(s){ obj[s] = (obj[s] || 0) + 1; }); return obj; } console.log(countAllCharacters('banana'));
This can be made shorter with .reduce()
:这可以用.reduce()
缩短:
function countAllCharacters(str) { return str.split("").reduce(function(obj, s){ obj[s] = (obj[s] || 0) + 1; return obj; }, {}); } console.log(countAllCharacters('banana'));
Note that (obj[s] || 0)
means to use obj[s]
's value if it is truthy, otherwise use 0
.请注意, (obj[s] || 0)
表示如果obj[s]
的值为真,则使用它,否则使用0
。 So the first time you encounter a particular letter obj[s]
will be undefined
, which is falsey, so then 0
will be used.因此,您第一次遇到特定字母obj[s]
将是undefined
,这是错误的,因此将使用0
。 The next time you encounter that letter obj[s]
will be 1
, which is truthy.下次你遇到那个字母obj[s]
将是1
,这是真的。
I'd use a reduce operation, like so我会使用减少操作,就像这样
const str = "banana" const charCounts = Array.from(str).reduce((counts, char) => { counts[char] = (counts[char] || 0) + 1 return counts }, Object.create(null)) console.info(charCounts)
Actually you can count by better performance, you loop more than you needed!实际上,您可以通过更好的性能来计算,您循环的次数超出了您的需要!
function countAllCharacters(str) { var a = str.split(""); var obj = {}; for(var j=0;j<a.length;j++){ if(typeof obj[a[j]] !== 'undefined'){ obj[a[j]]+=1; } else { obj[a[j]]=1; } } return obj; } console.log(countAllCharacters('banana'));
I think you need not to use a forEach
and a for
loop together when you can do it with only foreach
.我认为当你可以只使用foreach
时,你不需要同时使用forEach
和for
循环。 Here is the code.这是代码。
function countAllCharacters(str) { var a = str.split(""); var obj = {}; a.forEach(function(s) { if (obj[s]) { obj[s] = obj[s] + 1; } else { obj[s] = 1; } }); return obj; } console.log(countAllCharacters('banana'));
Hope it helps :)希望它有帮助:)
The problem here is that you assign the obj[a[j]] = count;
这里的问题是你分配了obj[a[j]] = count;
when the counting is not yet complete.当计数尚未完成时。 You should do change your function(s)
to this:您应该将您的function(s)
更改为:
function(s){
var count=0;
for(var j=0;j<a.length;j++){
if(s==a[j]){
count+=1;
}
}
obj[s]=count;
}
Another comment: you code is very inefficient, which is O(n^2)
.另一个评论:您的代码效率非常低,即O(n^2)
。 You can simplify it much further to get an O(n)
algorithm with this:您可以进一步简化它以获得O(n)
算法:
function(s){
if (obj[s] == undefined) {
obj[s] = 1;
} else {
obj[s] = obj[s] + 1;
}
}
Already so many friends submitted their opinions and cool solutions.已经有很多朋友提交了他们的意见和很酷的解决方案。 Here is my solution with the simplest code:这是我使用最简单代码的解决方案:
const src = 'banana'; const count = str => [...str].reduce((acc, val) => (acc[val] ? (acc[val]++) : (acc[val]=1), acc),{}); console.log(count(src));
.as-console-wrapper {min-height: 100%}
Hope you enjoy my code.希望你喜欢我的代码。 Thanks.谢谢。
I realize this isn't the prettiest, but I'm hoping it shows how you can use console to help debug loops.我意识到这不是最漂亮的,但我希望它展示了如何使用控制台来帮助调试循环。
function countAllCharacters(str) {
var a = str.split("");
var obj = {};
a.forEach(function(s){
console.log(s);
var count=0;
for(var j in a){
// commas can come in really handy and help avoid huge debug blocks.
console.log('_',j,s,a[j]);
if(s==a[j]){
console.log('count++');
count++;
}
obj[s] = count;
}
});
return obj;
}
console.log(countAllCharacters('banana'));
you have to bring obj[a[j]]=count
inside your if
statement.你必须在你的if
语句中引入obj[a[j]]=count
。
this should return correct results这应该返回正确的结果
function countAllCharacters(str) {
var a = str.split("")
var obj = {}
a.forEach(function(s){
var count=0
for(var j=0;j<a.length;j++){
if(s===a[j]){
count+=1
obj[a[j]]=count
}
}
})
return obj
}
console.log(countAllCharacters('banana'))
the increment in obj
must also satisfy the if
statement. obj
的增量也必须满足if
语句。
function countAllCharacters(str) {
let newArr = str.split(''); // splits the string into a new array
let obj = {}; // initiliza an empty object
newArr.forEach(char => (obj[char]) ? obj[char] += 1 : obj[char] = 1);
return obj;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.