首页 > 这段js代码

这段js代码

  下面这段

        return {
        ....
        }[String(angle).match(/[a-z]+$/)[0] || 'rad'](parseFloat(angle));
   的写法是什么意思?return后面跟个数组自执行? 
    
  function radians(angle) {
        if (typeof angle == 'number') return angle;
        return {
            rad: function(z) {
                return z;
            },
            deg: function(z) {
                return Math.PI / 180 * z;
            }
        }[String(angle).match(/[a-z]+$/)[0] || 'rad'](parseFloat(angle));
    }

{
    rad: function(z) {
        return z;
    },
    deg: function(z) {
        return Math.PI / 180 * z;
    }
}['rad']

上面的结果是

function(z) {
    return z;
}

函数当然可以执行了

str.match(regexp)

Return value
An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.

var str = 'For more information, see Chapter 3.4.5.1';
var re = /see (chapter \d+(\.\d)*)/i;
var found = str.match(re);

console.log(found);

// logs [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]

// 'see Chapter 3.4.5.1' is the whole match.
// 'Chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'.
// '.1' was the last value captured by '(\.\d)'.
// The 'index' property (22) is the zero-based index of the whole match.
// The 'input' property is the original string that was parsed.

第一次看到这种写法
炫技能还可以,真正给别人看还是写清楚点好


相当于:

var methods= {rad: function(){}, deg: function() {}};
var type = String(angle).match(/[a-z]+$/)[0] || 'rad';
return methods[type](parseFloat(angle));

写法还算奇怪,至少我见到这样的写法不多。目的就是,根据传进来的angle来判断是调用rad还是deg方法


return {
    //一堆函数
}[通过函数名选择要执行哪个函数](函数参数)

只是写的复杂了一点, 不要被细节迷惑了.

【热门文章】
【热门文章】