See the below snippets:
Snippet #1:
let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(arguments));
See the below snippets:
Snippet #1:
let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(arguments));
Snippet #2:
let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(error, data));
Expected log:
Values of (error, data)
, for example like:
null 'console.log("HELLO WORLD");\r\n'
When you try both these snippets, you will find that the Snippet #1 executes and logs some unexpected values for console.log(arguments)
but console.log(error, data)
logs proper values; values of (error, data)
.
Why and What was the value that is being logged for Snippet #1?
Share Improve this question asked Nov 5, 2016 at 8:07 Temp O'raryTemp O'rary 5,83815 gold badges53 silver badges114 bronze badges 2-
Should those snippets be runnable? Coz,
require
will not work – Rajesh Commented Nov 5, 2016 at 8:09 - See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?. – Felix Kling Commented Nov 5, 2016 at 14:59
2 Answers
Reset to default 10No binding of arguments
Arrow functions do not bind an arguments object Thus, arguments is simply a reference to the name in the enclosing scope.
From: MDN - Arrow functions
If you wish to use variadic arguments inside an arrow function, use the rest parameters syntax:
fs.readFile(process.argv[2], "utf8", (...args) => console.log(args));
@Tamas is smack on,
But a little tip for the OP, if you ever wonder what new javascript features from ES6 etc are doing. I paste the code into Babeljs.io try it out bit.
eg. Your code ->
https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Ces2015-loose%2Ces2016%2Ces2017%2Clatest%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&code=fs.readFile(process.argv%5B2%5D%2C%20%22utf8%22%2C%20(error%2C%20data)%20%3D%3E%20console.log(arguments))%3B%0D%0A
and then @Tamas code ->https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Ces2015-loose%2Ces2016%2Ces2017%2Clatest%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&code=fs.readFile(process.argv%5B2%5D%2C%20%22utf8%22%2C%20(...args)%20%3D%3E%20console.log(args))%3B
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744298561a4567384.html
评论列表(0条)