freeCodeCamp/curriculum/challenges/chinese-traditional/02-javascript-algorithms-an.../basic-javascript/passing-values-to-functions...

2.8 KiB
Raw Blame History

id title challengeType videoUrl forumTopicId dashedName
56533eb9ac21ba0edf2244bd 將值傳遞給帶有參數的函數 1 https://scrimba.com/c/cy8rahW 18254 passing-values-to-functions-with-arguments

--description--

函數的參數 parameters)在函數調用中充當傳入函數的輸入佔位符(也叫形參)。 函數調用時,參數可以爲一個或多個。 調用函數時輸入(或傳遞 "passed")的實際值被稱爲參數(arguments)。

這是帶有兩個參數的函數,param1param2

function testFun(param1, param2) {
  console.log(param1, param2);
}

然後我們可以調用 testFun,就像這樣: testFun("Hello", "World");。 我們傳入了兩個字符串參數, HelloWorld。 在函數中,param1 等於字符串 Hello 以及 param2 等於字符串 World。 請注意,testFun 函數可以多次調用,每次調用時傳遞的參數會決定參數的實際值。

--instructions--

  1. 創建一個名爲 functionWithArgs 的函數,它可以接收兩個參數,計算參數的和,將結果輸出到控制檯。
  2. 用兩個數字作爲參數調用函數。

--hints--

functionWithArgs 應該是一個函數。

assert(typeof functionWithArgs === 'function');

functionWithArgs(1,2) 應該輸出 3

if (typeof functionWithArgs === 'function') {
  capture();
  functionWithArgs(1, 2);
  uncapture();
}
assert(logOutput == 3);

functionWithArgs(7,9) 應該輸出 16

if (typeof functionWithArgs === 'function') {
  capture();
  functionWithArgs(7, 9);
  uncapture();
}
assert(logOutput == 16);

在定義 functionWithArgs 之後記得傳入兩個數字調用它。

assert(
  /functionWithArgs\([-+]?\d*\.?\d*,[-+]?\d*\.?\d*\)/.test(
    code.replace(/\s/g, '')
  )
);

--seed--

--before-user-code--

var logOutput = "";
var originalConsole = console
function capture() {
    var nativeLog = console.log;
    console.log = function (message) {
        if(message) logOutput = JSON.stringify(message).trim();
        if(nativeLog.apply) {
          nativeLog.apply(originalConsole, arguments);
        } else {
          var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
          nativeLog(nativeMsg);
        }
    };
}

function uncapture() {
  console.log = originalConsole.log;
}

capture();

--after-user-code--

uncapture();

if (typeof functionWithArgs !== "function") { 
  (function() { return "functionWithArgs is not defined"; })();
} else {
  (function() { return logOutput || "console.log never called"; })();
}

--seed-contents--


--solutions--

function functionWithArgs(a, b) {
  console.log(a + b);
}
functionWithArgs(10, 5);