我一直在尝试找出这个练习的答案,但一定有一个我看不到的错误。我将分享练习的描述、我的代码以及最后的输出。
描述:
现在我们将把每个数组的最长长度保存在一个名为 array_lengths 的新数组中
打开控制台并重新加载索引页以查看代码的结果。
编写一个函数 charFreq(),它接受一个字符串并构建其中包含的字符的频率列表。
作为一个条件,您必须使用对象 freqCounter。
将频率列表表示为 Javascript 对象。尝试使用 charFreq("abbabcbdbabdbdbabababcbcbab") 之类的东西。
CODE:
function charFreq(string) {
var array_lengths = [];
// compute frequencies of each value
for (var i = 0; i < string.length; i++) {
value = string[i];
if (value in array_lengths) {
array_lengths[value] ++;
} else {
array_lengths[value] = 1;
}
}
// make array from the frequency object to de-duplicate
var freqCounter = [];
for (value in array_lengths) {
freqCounter.push(value);
}
// sort the uniques array in descending order by frequency
function compareFrequency(a, b) {
return array_lengths[b] - array_lengths[a];
}
return freqCounter.sort(compareFrequency);
}
//OUTPUT:
// if I had it right I should get "true" from every of the following values of the function but the point is that I'm getting all false...where's the error?
counter = charFreq("abbabcbdbabdbdbabababcbcbab");
console.log(counter['a'] === 7);
console.log(counter.b === 14);
console.log(counter['c'] === 3);
两个问题
function charFreq( string ) {
var array_lengths = {}; // object
// compute frequencies of each value
for(var i = 0; i < string.length; i++) {
value = string[i];
if(value in array_lengths) {
array_lengths[value]++;
} else {
array_lengths[value] = 1;
}
}
return array_lengths;
}
//OUTPUT:
// if I had it right I should get "true" from every of the following values of the function but the point is that I'm getting all false...where's the error?
counter = charFreq("abbabcbdbabdbdbabababcbcbab");
console.log(counter);
console.log( counter['a'] === 7);
console.log( counter.b === 14);
console.log( counter['c'] === 3);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)