1
/**
 * @param array such as [1024, 2048, 20480, 102400]
 * @param unit such as M
 * @return return proper unit from units
 */
var units = ['M', 'G', 'TB', 'PB'];
function solveUnit(array, unit) { 
    var power, unitIndex;
    var lastChooseIndex = units.indexOf(unit);
    for(var i = 0, len = array.length; i < len; i++) {
        power = 1024; // set back to 1024
        unitIndex = units.indexOf(unit);
        while(Math.floor(array[i] / power) > 100 ) {
            unitIndex++;
            power = power * power;
        }
        if(unitIndex > lastChooseIndex) {
            lastChooseIndex = unitIndex;
        }   
    }
    return units[lastChooseIndex];
}
function formatArray(array, unit, _get) {
    if(unit == _get) {
        array.forEach(function(item) {
            console.log(item + ''+unit);
        });
        return array;
    }
    var gap = units.indexOf(_get) - units.indexOf(unit);
    var power = 1024;
    while(gap>1) {
        power = power * power;
        gap--;
    }
    var ret  = array.map(function(item) {
        console.log( (item/power).toFixed(1) + '' + _get );
        return (item/power).toFixed(1);
    });
    return ret;
}
// test
var array = [112640, 141312];
var unit = 'M';
var _get = solveUnit(array, unit);
formatArray(array, unit, _get);

Honwhy
7k 声望96 粉丝

神兽党有福了