1. 程式人生 > 實用技巧 >通過xxx.xxx.xxx字串來獲取巢狀物件中的某個屬性值;函式柯利化

通過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);

認真去感受一下,就知道差別了