Javascript pure function example with objects

前端 未结 2 1456
醉话见心
醉话见心 2021-01-21 13:15

I have the example below of an impure function. Note the variable a is outside of the function scope is being changed. To get around it, one could clone the object

2条回答
  •  抹茶落季
    2021-01-21 13:56

    Change the object:

    function transformObject(a) {			
        Object.keys(a).forEach(function (k) { a[k] *= 2; });
    }
    
    var a = {
            a : 1,
            b : 2
        };
    transformObject(a);		
    document.write('
    ' + JSON.stringify(a, 0, 4) + '
    ');

    Keep the object and return a new object with the result:

    function transformObject(a) {
        var b = {};
        Object.keys(a).forEach(function (k) { b[k] = a[k] * 2; });
        return b;
    }
    
    var a = {
            a : 1,
            b : 2
        },
        b = transformObject(a);		
    document.write('
    ' + JSON.stringify(a, 0, 4) + '
    '); document.write('
    ' + JSON.stringify(b, 0, 4) + '
    ');

提交回复
热议问题