6

数字千分位格式化

function format (num) {
    let [integer,decimal]=String(num).split('.');
    let regObj=/\d{1,3}(?=(\d{3})*$)/g;
    let arr=String(integer).match(regObj);
    return arr.join(',')+(typeof decimal=="undefined"?"":'.'+decimal);
}
console.log(format(1234567890.2323));

字符串中出现次数最多的字母

let str = "zhaochucichuzuiduodezifu";
str = str.split("").sort().join("");
let maxLen=0;
let match=null;
let key="";
let regExp=/(\w)\1*/g;
while (match =regExp.exec(str) ){
    if (match[0].length>maxLen){
        maxLen=match[0].length;
        key=match[1];
    }
}
console.log(`key:${key},count:${maxLen}`);

深度优先遍历树结构

var data={
    key1:"str1",
    key2:{
        key3:"key3",
        key4:"key4",
        key5:{
            key6:"key6"
        }
    }
}
function treeTraversal(data) {
    function f(prefix,data) {
        var keys=Object.keys(data);
        if(!/^\s*$/.test(prefix)){
            prefix+=" ";
        }
        keys.forEach((item,index)=>{
            if (typeof data[item] == "string"){
                console.log(prefix+item+" "+data[item]);
                return prefix+item+" "+data[item];
            }else{
                prefix+=item;
                return f(prefix, data[item]);
            }
        });
    }
    f("",data);
}
treeTraversal(data);

安静的木马
957 声望11 粉丝