gpt4 book ai didi

Javascript - 这两个对象之间有区别吗?

转载 作者:行者123 更新时间:2023-11-30 11:14:11 26 4
gpt4 key购买 nike

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

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 打破了这个规则。

关于Javascript - 这两个对象之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com