首页 > 其他 > 详细

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

时间:2020-09-06 19:48:42      阅读:71      评论:0      收藏:0      [点我收藏+]

 

// 用字符串路径来访问对象的成员(思路)
        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);

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

 

 

 

 

 

 

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

原文:https://www.cnblogs.com/fqh123/p/13622601.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!