When I run solve-3 with --l=4 and --w=4, function rectangle.perimeter and rectangle.area output NaN. Why? To me it seemed like the integers entered are being converted to strings hence why I added Number(), but that did not change anything.
File 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);
}
}
File 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));
Look at the functions you've defined:
perimeter: function(l,w) {
return (2*(l+w));
},
You expect this function to take two arguments.
Then you call it with no arguments:
rectangle.perimeter()
The arguments you're defining are shadowing the ones in the upper scope of your rect-2 file. A simple workaround is just to remove the function arguments:
perimeter: function() {
return (2*(l+w));
},
area: function() {
return (l*w);
}
Now these two functions are said to "close over" the l
and w
variables present in the upper scope.
While wrapping a string in Number()
will technically work in this case, note that yargs
lets you specify the types of user input values on the command line, such as the .number() syntax:
var argv = require('yargs')
.number(['l','w'])
.demand(['l','w'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.