gpt4 book ai didi

javascript - Functional Javascript 书籍示例中的错误

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

我正在通读 Michael Fogus 的Functional JavaScript 一书,但书中的一个示例无法正常工作。这是代码:

function existy(x) {
return x != null;
};

function truthy(x) {
return (x !== false) && existy(x);
};

function cat() {
var head = _.first(arguments);
if (existy(head))
return head.concat.apply(head, _.rest(arguments));
else
return [];
};

function construct(head, tail) {
return cat([head], _.toArray(tail));
};

function rename(obj, newNames) {
return _.reduce(newNames, function(o, nu, old) {
console.log("o: " + o);
console.log("nu: " + nu);
console.log("old: " + old);
if (_.has(obj, old)) {
o[nu] = obj[old];
return o;
}
else
return o;
},
_.omit.apply(null, construct(old, _.keys(newNames))));
};

rename({a: 1, b: 2}, {'a': 'AAA'});
// => {AAA: 1, b: 2}

除了 rename() 之外的所有函数都可以正常工作。本质上,目标是获取一个对象并返回该对象,该对象的属性名称已用 newName 对象更新。我不太了解它,但是 reduce 方法看起来没有正确的参数。这是我在调用 rename() 时遇到的错误:

ReferenceError: old is not defined

如果您能帮助我理解为什么它不起作用,我们将不胜感激!

最佳答案

function rename(obj, newNames) {
return _.reduce(newNames, function(o, nu, old) {
console.log("o: " + o);
console.log("nu: " + nu);
console.log("old: " + old);
if (_.has(obj, old)) {
o[nu] = obj[old];
return o;
}
else
return o;
},
_.omit.apply(null, construct(old, _.keys(newNames))));
}

调用时执行

_.reduce(newNames, function(o, nu, old) {
console.log("o: " + o);
console.log("nu: " + nu);
console.log("old: " + old);
if (_.has(obj, old)) {
o[nu] = obj[old];
return o;
}
else
return o;
},
_.omit.apply(null, construct(old, _.keys(newNames))));

调用

_.omit.apply(null, construct(old, _.keys(newNames)))

old只存在于_.reduce的回调中。如果它是第一个对象,您可以使用 newNames[0]

但是我不相信一本在函数定义后加上分号的书......


就我个人而言,如果我要“功能性”地实现它,它看起来像这样:

function objectMap(obj, func) {
var result = {};

for (var x in obj) {
if (obj.hasOwnProperty(x)) {
var r = func(x, obj[x]);
result[r[0]] = r[1];
}
}

return result;
}

function rename(obj, newNames) {
return objectMap(obj, function(k, v) {
return [newNames[k] || k, v];
});
}

关于javascript - Functional Javascript 书籍示例中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627517/

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