Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一段画蛇添足的代码 °(°ˊДˋ°) ° #2

Open
luokuning opened this issue Dec 2, 2015 · 0 comments
Open

一段画蛇添足的代码 °(°ˊДˋ°) ° #2

luokuning opened this issue Dec 2, 2015 · 0 comments
Labels

Comments

@luokuning
Copy link
Owner

前两天因为某个功能写了这么一段代码:

            /*...*/
            var parseStr = function(str) {
                    if (str != null && (typeof str['split'] === 'function')) {
                        var _t1 = str.split(','),
                            i, _t2;
                        for (i = 0; i < _t1.length; i++) {
                            [].splice.bind(_t1, i, 1).apply(_t1, _t1[i].split(','));
                        }
                        _t2 = _t1.filter(function(t) {
                            return t.search(/\S/) > -1;
                        });
                        return _t2;
                    } else {
                        throw {
                            msg: 'parseStr 参数需要是字符串或者字符串对象'
                        }
                    }
                }
                /*...*/

看上去是不是感觉很乱?还有中文逗号是什么鬼?没有类型声明的语言代码看起来确实麻烦,而且还没有注释,毕竟我喜欢写代码不写注释,但是最讨厌别人写代码不写注释:laughing:。开个玩笑,平常写代码的时候建议大家还是多写点注释,否则为了省事最后麻烦的还是自己。

说了这么多,其实当时想要实现的就是对于任何一段字符串,以中英文 (全/半角) 的逗号来分隔成数组,好进行下一步处理,然后才写了这么一段看上去唬人的代码。突然有一天回过头来看代码的时候想起来字符串的split方法是支持正则表达式的,那为何不改用split呢?TC39说split方法的参数要支持正则的形式,于是有了这段代码:

            /*...*/
            var parseStr = function(str) {
                    if (str != null && (typeof str['split'] === 'function')) {
                        var arr;
                        arr = str.split(/,|,/);
                        return arr;
                    } else {
                        throw {
                            msg: 'parseStr 参数需要是字符串或者字符串对象'
                        }
                    }
                }
                /*...*/

所以最开始的那一大坨代码就相当于 str.split(/,|,/) 这一行要完成的功能。感觉自己这一次很好的诠释画蛇添足这个成语的精髓:sweat_smile: !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant