Javascript 代码效率

标签 javascript jquery

我不确定在这里问这个问题是否合适。如果没有,请投票给我。但我正在寻找有关我的纵横比函数效率的意见。以下是确定纵横比并限制图像大小的函数。我是怎么做到的?

function constrainTwoNumbers(options){

d = {
    dir: 'either', // direction: 'auto', 'vertical' or 'horizontal'. What side of the image do you want to constrain?
    orgw:0,
    orgh:0,
    target:100,
}

// merge the options with the default values
o = $.extend(d, options);

// create object to write results into
var result = [];

switch(o.dir){
    case 'either':      
        // no direction is set, limit the largest side.
        // determine what the orientation is.
        if(o.orgw > o.orgh){ //landscape
            aspect = o.orgw / o.target;
        }else if(o.orgw < o.orgh){ //portrait
            aspect = o.orgh / o.target;
        }else if(o.orgw === o.orgh){ // the image is square. Just pass both dimensions as targeted
            result.w = o.target;
            result.h = o.target;
            return result;
        }                   
        break;
    case 'horizontal':      
            aspect = o.orgw / o.target;
        break;
    case 'vertical':            
            aspect = o.orgh / o.target;
        break;
}

result.w = Math.round(o.orgw / aspect);
result.h = Math.round(o.orgh / aspect);     
return result;
}

最佳答案

你可以将它压缩成一个if/else

function constrainTwoNumbers(options){

    var d = {
        dir: 'either', // direction: 'either', 'vertical' or 'horizontal'. What side of the image do you want to constrain?
        orgw:0,
        orgh:0,
        target:100
    };

    // merge the options with the default values
    var o = $.extend(d, options);

    // create object to write results into
    var result = [];
    if ((o.dir === 'either' && o.orgw > o.orgh) || (o.dir === 'horizontal'))
    {
      aspect = o.orgw / o.target;
    }
    else
    {
      aspect = o.orgh / o.target;
    }

    result.w = Math.round(o.orgw / aspect);
    result.h = Math.round(o.orgh / aspect);     
    return result;
}

关于Javascript 代码效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4407445/

相关文章:

php - 从 php 自动建议

javascript - jCarousel 显示选择了类的元素

javascript - Ajax-发送前

javascript - 使用 Metrics Graphics.js 时出现 TypeError

javascript - 清除有关 JQuery Ajax 的一些内容

javascript - 在选择时使用参数触发完整日历刷新

javascript - 如何在用户滚动到页面底部时启动 jQuery 事件?

javascript - 文本字段的正则表达式

php - 我做错了什么 AJAX 自动完成标记实现?

javascript - 将文本区域内容下载为批处理文件 onclick