Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

Javascript function - Can you give arguments like this?

can anyone figure out what this possibly means?

Below code is to sum all the arguments, and I called the function like 'addTogether(2)(3)' then it works....?

For my understanding, calling a function should look like this 'addTogether(2, 3)'. put all the arguments in a pair of parentheses not two pairs of parentheses??

Could anyone explain why it worked and how it works?

I did console.log to figure this out, If I console.log(arguments) the result would be { '0': 2 }

function addTogether() {
  console.log(arguments) // result { '0': 2 }
  var args = Array.from(arguments);
  console.log(args) //result [2]
  
  return args.some(n => typeof n !== "number")
    ? undefined
    : args.length > 1
    ? args.reduce((acc, n) => (acc += n), 0)
    : n => (typeof n === "number" ? n + args[0] : undefined);
}

// test here
console.log(addTogether(2)(3)); // result 5
question from:https://stackoverflow.com/questions/65915954/javascript-function-can-you-give-arguments-like-this

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function addTogether(args) { 
  console.log(args)
  
  return args.some(n => typeof n !== "number")
    ? undefined
    : args.length > 1
    ? args.reduce((acc, n) => (acc += n), 0)
    : n => (typeof n === "number" ? n + args[0] : undefined);
}

Then call it like addTogether([1, 2])

[] Is a array, everything in it, seperated with a comma, is an item in the array. You can only have the same datatype in the array. In the (), where the function is defined, is where you should define what data you want to get, when the function is called.

If you want to test it quick, copy and paste it into the developer console in your browser, and call the function after


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...