通过xxx.xxx.xxx字符串来获取嵌套对象中的某个属性值;函数柯利化

 

// 用字符串路径来访问对象的成员(思路)
        function getValueByPath( obj,path ){
            let paths = path.split(".");//[xxx,yyy,zzz,...]
            // 先取得obj.xxx 再取得 obj.xxx.yyy 再取得 obj.xxx.yyy.zzz
            // let res = null;
            // res = obj[ paths[ 0 ] ];
            // res = res[ paths[1] ];
            // res = res[ paths[2] ];
            let res = obj;
            let prop;
            while( prop = paths.shift()){//把数组中的第0项取出来
                res = res[ prop ];
            }
            return res;
        }
        var o = {
            a:{
                b:{
                    c:{
                        d:{
                            e:"正确了"
                        }
                    }
                }
            }
        }
        let aa = getValueByPath(o,"a.b.c.d.e");
        console.log(aa);

 

今天看到了,vue中是把这个  函数柯利化  了,之前只是简单了解过,平时没用过,今天来理解的用一下;

函数柯里化:柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术。

这样可以让函数更加灵活,降低耦合度,可能平时感受不到,但是这里理解一下,说不定什么时候就可能用到:

将上面的函数 柯利化一下:

// 柯利化的好处是  减少函数的调用
        function createGetValueByPath( path ){
            let paths = path.split(".");
            return function getValueByPath ( obj ){
                let res = obj;
                let prop;
                while( prop = paths.shift()){//把数组中的第0项取出来
                    res = res[ prop ];
                }
                return res;
            }  
        }
        let getValueByPath = createGetValueByPath('a.b.c.d')
        var o = {
            a:{
                b:{
                    c:{
                        d:{
                            e:"正确了"
                        }
                    }
                }
            }
        }
        let aa = getValueByPath(o);
        console.log(aa);

认真去感受一下,就知道差别了

 

 

 

 

 

 

posted @ 2020-09-06 18:11  古墩古墩  Views(574)  Comments(0Edit  收藏  举报