这是工作中的测试任务。
一位农民有兔子。每只兔子都是它的重量。到时候,他杀死了他们的职能cut(rabbit)
。
你必须写一个cut的函数,使它具有外观
cut(rabbit1)(rabbit2)...(rabbitN)
并推断出兔子的总质量和数量。
例如:
var rabbit1 = {weight: 5},
rabbit2 = {weight: 4};
console.log(cut(rabbit1)(rabbit2));
在控制台中,我们将看到“9公斤兔子或2件”。
JSFiddle - https://jsfiddle.net/sjao7ut8/
我如何编写函数cut()
?
答案 0 :(得分:7)
您可以使用链接,一个流畅的界面,它返回您调用的函数,直到环境需要原始值。
function cut(rabbit) {
var weight = 0,
count = 0,
fn = function (o) {
weight += o.weight;
count++;
return fn;
};
fn.toString = function () {
return weight + ' kg of rabbits or ' + count + ' piece' + (count > 1 ? 's' : '');
}
return fn(rabbit);
}
var rabbit1 = { weight: 5 },
rabbit2 = { weight: 4 };
console.log(cut(rabbit1)(rabbit2));
答案 1 :(得分:0)
你需要做的是使用递归调用,它返回一个函数并使用arguments.callee
这样的事情应该可以胜任:
function cut(firstRabbit) {
var mass = firstRabbit.weight;
return function(nextRabbit) {
if (typeof nextRabbit !== 'undefined') {
mass += nextRabbit.weight;
return arguments.callee;
} else {
return mass;
}
};
}
示例用法(记得在最后添加()):
var rabbit1 = {weight: 5},
rabbit2 = {weight: 4};
console.log(cut(rabbit1)(rabbit2)());
答案 2 :(得分:0)
您可以尝试以下代码:
var farmer = {
cut: function(rabits) {
var cutWeight = 10;
var totalCuts = 0;
var totalWeight = 0;
var count = rabits.length;
for(var i=0; i < count; i++) {
var rabit = rabits[i];
if(rabit.weight >= cutWeight) {
totalWeight += rabit.weight;
if(totalCuts === 0) {
totalCuts = 1;
}
else {
totalCuts += 1;
}
}
}
console.log(totalWeight + "Kg of Rabits and " + totalCuts + "cuts.")
}
};
farmer.cut([{weight: 11}, {weight: 5}, {weight: 13}]); // Call the function
希望这会对你有所帮助。
答案 3 :(得分:-1)
Function.prototype.toString = function() {
return Function.prototype.rabbitsWeight + "кг кроликов или " + Function.prototype.rabbitsCount + " штук";
};
Function.prototype.rabbitsWeight = 0;
Function.prototype.rabbitsCount = 0;
window.rabbitsCut = eval("new Function('rabbit', 'Function.prototype.rabbitsWeight += rabbit.weight; ++Function.prototype.rabbitsCount; return eval(window.rabbitsCut);');");
var cut = window.rabbitsCut;
console.log(cut({weight: 5})({weight: 4}));