javascript - 此函数如何处理缺少的参数

标签 javascript

当回调函数需要 2 个(选择器和数据)时,如何使用一个参数?为什么它不抛出错误?

let links = document.querySelectorAll("a");
        links.forEach(function(link){
            link.addEventListener("click",function(e){
                e.preventDefault();
                ajax("get",e.target.href,render)
            })
        })
        function ajax(url,metodo,callback){
            let xhr = new XMLHttpRequest
            xhr.open(metodo,url)
            xhr.addEventListener("load",function(){
                if(xhr.status==200){
                    callback(xhr.response)
                }
            })
            xhr.send()
        }
        function render(selector,data){
            document.querySelector(selector).innerHTML = data
        }

最佳答案

在 javascript 中,不必使用与函数定义中定义的相同数量的参数进行调用。如果我们在函数定义中没有定义默认参数值,那么参数就变成了未定义的类型。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Starting with ECMAScript 2015, there are two new kinds of parameters: default parameters and rest parameters.

Default parameters: In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is where default parameters can help.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If in the following example, no value is provided for b in the call, its value would be undefined when evaluating a*b and the call to multiply would have returned NaN. However, this is caught with the second line in this example:

function multiply(a, b) {
  b = typeof b !== 'undefined' ?  b : 1;

  return a * b;
}

multiply(5); // 5

With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default value for b in the function head:

function multiply(a, b = 1) {
  return a * b;
}

multiply(5); // 5

有关更多详细信息,请参阅引用中的默认参数。

Rest parameters: The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the example, we use the rest parameters to collect arguments from the second one to the end. We then multiply them by the first one.

 function multiply(multiplier, ...theArgs) {
  return theArgs.map(x => multiplier * x);
}

var arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]

参数对象:

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

 function myConcat(separator) {
   var result = ''; // initialize list
   var i;
   // iterate through arguments
   for (i = 1; i < arguments.length; i++) {
      result += arguments[i] + separator;
   }
   return result;
}

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

// returns "red, orange, blue, "
myConcat(', ', 'red', 'orange', 'blue');

// returns "elephant; giraffe; lion; cheetah; "
myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');

// returns "sage. basil. oregano. pepper. parsley. "
myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');

为了使它抛出错误,如果没有在函数中传递相同数量的参数,typescript可以使用。

关于javascript - 此函数如何处理缺少的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51624539/

相关文章:

javascript - 选择单选按钮后重定向到特定页面

javascript - 如何在 Javascript 中捕获用户操作所消耗的时间?

javascript - 选中复选框时 Twitter Bootstrap 3 崩溃

javascript - 如何在选中复选框时启用选项卡

javascript - 迁移学习 Tensorflow.js 大小/形状错误

javascript - 如何在 D3.js 中强制气泡的重力

javascript - JavaScript 语法部分的左因式分解

javascript - jQuery Texfill 不适用于具有相同选择器的所有元素

javascript - Express Gateway 启用日志

javascript - 在使用 grunt usemin 和 rev 时使用 SourceMaps Uglify