Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...