当我使用--l=4 和--w=4 运行solve-3 时,函数rectangle.perimeter 和rectangle.area 输出NaN。为什么?对我来说,输入的整数似乎被转换为字符串,因此我添加了 Number(),但这并没有改变任何东西。
文件 1:rect-2.js
module.exports = function(l,w,callback) {
try {
if (l < 0 || w < 0) {
throw new Error("Rectangle dimensions should be greater than zero: l = " + l + ", and w = " + w);
}
else
callback(null, {
perimeter: function(l,w) {
return (2*(l+w));
},
area: function(l,w) {
return (l*w);
}
});
}
catch (error) {
callback(error,null);
}
}
文件 2:solve-3.js
var argv = require('yargs')
.usage('Usage: node $0 --l=[number] --w=[number]')
.demand(['l','w'])
.argv;
var rect = require('./rect-2');
function solveRect(l,w) {
console.log("Solving for rectangle with length: " + l + " and width: " + w);
rect(l,w, function(err,rectangle) {
if (err) {
console.log(err);
}
else {
console.log("The area of a rectangle with length = "+l+" and width = "+w+" is "+rectangle.area());
console.log("The perimeter of a rectangle with length = "+l+" and width = "+w+" is "+rectangle.perimeter());
}
});
};
solveRect(Number(argv.l),Number(argv.w));