手记

面试题:用js实现读取出字符串中每个字符重复出现的次数?

如字符串arr="abcdaabc",请用js读取出arr字符串中每个字母重复出现的次数分别是多少?

  var arr = 'abcdaabc';
  var info = arr.split('').reduce((p, k) => (p[k]++ || (p[k] = 1), p), {});
  console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }

</br>
坐等更好方案:
var arr = 'abcdaabc';
var info = arr.split('').reduce((p, k) => (p[k]++ || (p[k] = 1), p), {});
console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }
</br>
reduce不兼容低版本哦,还有比这个更简洁的吗?
var temp = {};
'abcdaabc'.replace(/(\w{1})/g,function($1){
temp[$1] ? temp[$1]+=1 : temp[$1] = 1;
})
console.log(temp) // {a: 3, b: 2, c: 2, d: 1}
</br>
var obj = {}
'abcdaabc efgh'.replace(/(\w)/g,function(word,p){
obj[p[0]] ? obj[p[0]]+=1 : obj[p[0]] =1
})
console.log(obj)
</br>
</br>
var arr="abcdaabc"
var count = {};
var i,k

for(i=0;i<arr.length;i++){
var chr = arr.charAt(i);
if( typeof count[chr] === "undefined"){
count[chr] = 1;
}else{
count[chr]++;
}
}
console.log(count)
for(k in count){
if(count.hasOwnProperty(k)){
console.log("%s:%d",k,count[k]);
}
}
</br>
</br>
var str = "addbsnjfsss";
var strArray = str.split("");
var returnObj = {};
for(var i = 0; i < strArray.length; i++) {
if(returnObj[strArray[i]]) {
returnObj[strArray[i]] = parseInt(returnObj[strArray[i]]) + 1;
} else {
returnObj[strArray[i]] = 1;
}
}
for(var p in returnObj) {
console.log(p + " : " + returnObj[p]);
}
</br>
</br>
var str = 'abcdacbacxjkl';

var Counter = new Counter();
Counter.count(str);
console.log(Counter.getResult()); //{a: 3, b: 2, c: 3, d: 1, x: 1…}
function Counter() {
var temp = {};
var push = function(item) {
temp[item] = temp[item] ? ++temp[item] : 1;
}

this.count = function(str) {
    str.split('').forEach( function(item) {
        push(item);
    });
}

this.getResult = function() {
    return temp;
}

}
</br>
</br>
var str='sadzewrwewasdfaxzvzxfasdaswe';

function count(s, e)
{
if(s>e)
{
return {};
}
else if(s==e)
{
var x=str.charAt(s);

    var json={};

    json[x]=1;

    return json;
}

var c=Math.floor((s+e)/2);

var l=count(s, c);        
var r=count(c+1, e);    

var result=l;

for(var i in r)
{

    if(result[i])    
    {
        result[i]+=r[i];
    }
    else            
    {
        result[i]=r[i];
    }
}

return result;

}

console.log(count(0, str.length-1));

</br>
</br>

0人推荐
随时随地看视频
慕课网APP

热门评论


<script>

var ary = "qwertyuiopasdfvvvdvvd";

var obj = {};

var i = 0;

ary1 = ary.toLocaleLowerCase();

for(i = 0; i < ary1.length; i++)

{

key = ary1[i];

if(obj[key])

{

obj[key]++;

}

else

{

obj[key] = 1;

}

}

for(var key in obj) //遍历这个对象

{

console.log(key + "这个字母出现了" + obj[key] + "次");

}

</script>




查看全部评论