gpt4 book ai didi

javascript - 检查函数参数是否为 JavaScript 中的默认参数

转载 作者:行者123 更新时间:2023-11-28 15:42:24 25 4
gpt4 key购买 nike

假设我有一个这样的函数

function functionName(parameter = 5) {

}

是否可以在函数内部检查该参数的值是否已更改?我的意思是,如果有人像这样调用函数“functionName()”,则默认值不会改变,但如果像这样调用“functionName(10)”,它的值就会不同,

最佳答案

我并不是说这是一个好主意(如果您确实需要知道,我可能只是不使用默认参数并检查未定义),但您可以 通过查看 arguments 伪数组来判断。示例:

  function myFunction(parameter = 5) {
if (arguments.length === 0) {
console.log("parameter = " + parameter + " (DEFAULT)");
}
else {
console.log("parameter = " + parameter + " (provided)");
}
}
myFunction();
myFunction(5);
myFunction(6);

输出

parameter = 5 (DEFAULT)parameter = 5 (provided)parameter = 6 (provided)

As you can see, you can tell if you know that parameter is the first argument, and arguments.length is 0. Or if you had function myFunction(a = 5, b = 6, c = 7) you'd know c had been defaulted if arguments.length was <= 2.

The arguments section of the draft specification was until the most recent version mostly just a copy of the ES5 spec, but the April 2014 has been updated with the details of the arguments changes. I haven't had a chance to slog through the turgid spec-prose, but I expect this is covered in there somewhere.

Full Live Example - Only works in recent Firefox

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Default Args</title>
</head>
<body>
<script>
(function() {
"use strict";
function myFunction(parameter = 5) {
if (arguments.length === 0) {
display("parameter = " + parameter + " (DEFAULT)");
}
else {
display("parameter = " + parameter + " (provided)");
}
}
myFunction();
myFunction(5);
myFunction(6);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>

关于javascript - 检查函数参数是否为 JavaScript 中的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23382387/

25 4 0
文章推荐: javascript - 删除然后将相同的元素添加到 Packery JS
文章推荐: 用于切换图像切换按钮类的Javascript
文章推荐: html - 纯 CSS Masonry 布局中框底部的奇怪间距?
文章推荐: html - 如何使显示 : table-cell be 100% 内的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com