我在玩一些函数,我注意到这两个函数在纯函数中似乎有不同的输出。我认为这两个输出不同是正确的吗?

counter = 0;
function createObject1(name, calories, fat, carbs, protein) {
    counter += 1;
    return { id: counter, name, calories, fat, carbs, protein };
}

function createObject2(...args) {
    counter += 1;
    var data = {};
    data['id'] = counter;
    var headers = args[args.length - 1];
    for (var i = 0; i < args.length-1; i++) {
        data[headers[i]] = args[i]
    }
    return data
}

// How I'm calling them
createObject1('Cupcake', 305, 3.7, 67, 4.3);
createObject2('Cupcake', 305, 3.7, 67, 4.3, ["name","calories","fat","carbs","protein"]);


谢谢你的帮助! :-)

最佳答案

好吧,让我们尝试一下:



counter = 0;
function createObject1(name, calories, fat, carbs, protein) {
    counter += 1;
    return { id: counter, name, calories, fat, carbs, protein };
}

function createObject2(...args) {
    counter += 1;
    var data = {};
    data['id'] = counter;
    var headers = args[args.length - 1];
    for (var i = 0; i < args.length-1; i++) {
        data[headers[i]] = args[i]
    }
    return data
}

console.log(JSON.stringify(createObject1('Cupcake', 305, 3.7, 67, 4.3)));
console.log(JSON.stringify(createObject2('Cupcake', 305, 3.7, 67, 4.3, ["name","calories","fat","carbs","protein"])));





输出为:

{"id":1,"name":"Cupcake","calories":305,"fat":3.7,"carbs":67,"protein":4.3}
{"id":2,"name":"Cupcake","calories":305,"fat":3.7,"carbs":67,"protein":4.3}


如果用纯函数表示在函数编程中使用的概念(对于给定的输入始终返回相同输出的函数),则这些函数不是纯函数。纯函数必须仅依赖其参数作为输入,因此全局变量counter违反了此规则。

09-27 03:51