[英]Setting Javascript Function Parameters inside the function parenthesis
This is so simple I forgot how to do it. 这是如此简单,我忘了怎么做。 I've always passed variables to a function hence it's param's were pre-set, now I need to set the param's when declaring the function, but don't remember the setup.
我一直将变量传递给函数,因此已预先设置了参数,现在在声明函数时需要设置参数,但不记得设置了。
I'm looking for the working version of this: 我正在寻找这样的工作版本:
function(a,b=4){return a-b;}
Where the b
param' of the function is set when the function is declared. 在声明函数时设置函数的
b
参数的位置。
If I remember rightly it's like setting a default for b
if the function has no second argument: 如果我没记错的话,就像函数没有第二个参数时,为
b
设置默认值一样:
function(a,b){b=b || 4; return a-b;}
Thanks for all your help but it seems it's impossible in js without ECMAScript 6 . 感谢您的所有帮助,但是如果没有ECMAScript 6 ,似乎在js中是不可能的。 Your answers are getting a bit off topic though... I really needed the values set in the paren's.
但是,您的答案有点偏离主题了……我真的需要在括号中设置的值。
To keep it on topic... my initial problem is sending parameters to a setTimeout
function. 为了使之保持话题...我的最初问题是将参数发送到
setTimeout
函数。 Ok so I have a <div>
with a .gif
background, when clicked it's background changes, this second animation runs for exactly 8 seconds and then the background changes again to a final .gif
. 好的,我有一个
.gif
背景为<div>
的背景,单击它时背景发生变化,第二个动画恰好运行了8秒钟,然后背景再次变为最终的.gif
。 so it's a 3 stage animation, simple... thing is the 8sec gap, I figured a setTimeout
would work but I can't pass any param's to the 'sto' function to reference said <div>
. 所以这是一个3阶段的动画,很简单...就是8秒的间隔,我认为
setTimeout
可以工作,但是我无法将任何参数传递给'sto'函数来引用<div>
。
If you know of any timer events that can help then be my guest, this is as far as I've got. 如果您知道有什么定时器事件可以帮助我,请按我的意愿做。 My original code is below... it fails at
function(p = cha)
. 我的原始代码如下...它在
function(p = cha)
处失败。
for(var i = 0; i < 5; i++){
var cha = document.createElement('div');
$(cha).css('background','url(img/stand.gif)');
cha.addEventListener('click',function(){
$(cha).css('background','url(img/walk.gif)');
setTimeout(function(p = cha){
$(p).css('background','url(img/walk.gif)');
},8000);
});
}
function(a,b){b=b || 4; return a-b;}
This is the typical way to default params in ES5. 这是在ES5中默认参数的典型方法。 However I would advise changing this to check b's typs a little more strictly, because 0 will be considered a falsey value by the
||
但是,我建议更改此设置以更严格地检查b的类型,因为
||
会将0视为假值。 operator 算子
function(a,b){
b = typeof b === 'undefined' ? 4 : b;
return a-b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.