javascript - 优化判别区域的函数

查看:53
本文介绍了javascript - 优化判别区域的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

//根据坐标位置返回index
Jigsaw.prototype.moveboxPosition = function(position) {
    if (this.scope(position.x, 0, 100) && this.scope(position.y, 0, 100)) {
        return 0
    } else if (this.scope(position.x, 100, 200) && this.scope(position.y, 0, 100)) {
        return 1
    } else if (this.scope(position.x, 200, 300) && this.scope(position.y, 0, 100)) {
        return 2
    } else if (this.scope(position.x, 0, 100) && this.scope(position.y, 100, 200)) {
        return 3
    } else if (this.scope(position.x, 100, 200) && this.scope(position.y, 100, 200)) {
        return 4
    } else if (this.scope(position.x, 200, 300) && this.scope(position.y, 100, 200)) {
        return 5
    } else if (this.scope(position.x, 0, 100) && this.scope(position.y, 200, 300)) {
        return 6
    } else if (this.scope(position.x, 100, 200) && this.scope(position.y, 200, 300)) {
        return 7
    } else if (this.scope(position.x, 200, 300) && this.scope(position.y, 200, 300)) {
        return 8
    } else {
        return false
    }
};
//判断数值是否在给定区间
Jigsaw.prototype.scope = function(num, min, max) {
    if (num >= min && num <= max) {
        return true
    } else {
        return false
    }
};

以上代码是用来判断拖拽的div落在九宫格的哪个区域,如果有100个区域,那岂不是要99个else if,请问如何优化这段代码?

解决方案

供参考:

function moveboxPosition(position) {
    // 算出落点在第m行,第n列
    // 每行有a列,返回 m * a + n
    return Math.floor(position.x/100) * 3 + Math.floor(position.y/100);
}

这篇关于javascript - 优化判别区域的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆