How to make function parameter constant in JavaScript?(如何在 JavaScript 中使函数参数保持不变?)
问题描述
我想要做的是尽可能多地使用不可变变量,从而减少我的代码中移动部分的数量.我只想在必要时使用var"和let".
What I want to do is to use as many immutable variables as possible, thus reducing the number of moving parts in my code. I want to use "var" and "let" only when it's necessary.
这行不通:
function constParam(const a){
alert('You want me to '+a+'!');
}
有什么想法吗?
推荐答案
函数参数在 ES6 中将保持可变绑定(如 var
),对此您无能为力.您得到的最佳解决方案可能是解构 arguments
const
初始化中的对象:
Function parameters will stay mutable bindings (like var
) in ES6, there's nothing you can do against that. Probably the best solution you get is to destructure the arguments
object in a const
initialisation:
function hasConstantParameters(const a, const b, const c, …) { // not possible
…
}
function hasConstantParameters() {
const [a, b, c, …] = arguments;
…
}
请注意,此函数将具有不同的元数 (.length
),如果需要,您必须声明一些占位符参数.
Notice that this function will have a different arity (.length
), if you need that you'll have to declare some placeholder parameters.
这篇关于如何在 JavaScript 中使函数参数保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中使函数参数保持不变?


- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01