當我用--l = 4和--w = 4運行solve-3時,函數rectangle.perimeter和rectangle.area輸出NaN。爲什麼? 對我來說,似乎輸入的整數正在轉換爲字符串,因此我添加了Number(),但這並沒有改變任何東西。node.js(yargs)數字是作爲字符串輸入的嗎?
文件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:解決-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));
你應該使用' parseInt()'或'parseFloat()'將字符串轉換爲數字。 – generalhenry