簡體   English   中英

如何在 Java 腳本中的函數中的參數數組上應用 For-Each 循環

[英]How to apply For-Each Loop on Argument Array in Functions in Java Script

我的代碼不起作用。 我想對用戶在 arguments 中給出的數字求和。

所以我在這里使用參數 Object 但我無法獲取錯誤是什么。

    // The Argument Object 
function myFunc()
{
    console.log("You give Total Numbers : "+arguments.length);
    let sum = 0;

    console.log("Sum is : ");
    arguments.forEach(element => {
        sum += element;
    });


    console.log(sum);
}

myFunc(10,20);
myFunc(10,20,30);
myFunc(10,20,30,40);

你可以試試這個解決方案:

/**
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
 *
 * @param  {array} args ...args is the rest parameters. It contains all the arguments passed to the function.
 */
function myFunc (...args) {
  console.log(`You give Total Numbers : ${args.length}`);
  /**
   * Reduce is a built-in array method that applies a function against an accumulator and each element
   * in the array (from left to right) to reduce it to a single value.
   *
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
   */
  const sum = args.reduce((acc, curr) => acc + curr, 0);
  console.log('Sum is :', sum);
};

myFunc(10, 20);
myFunc(10, 20, 30);
myFunc(10, 20, 30, 40);

Output

You give Total Numbers : 2
Sum is : 30
You give Total Numbers : 3
Sum is : 60
You give Total Numbers : 4
Sum is : 100

嘗試這個:

function myFunc(...arguments)
{
    console.log("You give Total Numbers : "+arguments.length);

    console.log("Sum is : ");
     let sum = 0;
    arguments.forEach(element => {
        sum += element;
    });


    console.log(sum);
}

嘗試這個:

function myFunc() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
}
console.log(
    `
    Total Number : ${arguments.length}
    Sum : ${sum}
    `
);

}

myFunc(10 , 20 , 30 , 40);

像這樣輸出:

Total Number : 4
Sum : 100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM