var i=0;
function mul()
{
var qty = document.getElementsByClassName("qty");
var rs = document.getElementsByClassName("rs");
var amt = document.getElementsByClassName("amt");
var mul=(qty[i].value)*(rs[i].value);
amt[i].setAttribute("value",mul);
sp.appendChild(iteminp);
sp.appendChild(qtyinp);
sp.appendChild(rsinp);
sp.appendChild(amtinp);
i++;
}
在上面的程序中,我想要' i'应该在每次调用函数时增加它,并且它应该在整个程序中像静态变量一样。 怎么做?
答案 0 :(得分:1)
您可以拥有一个名为globals.js的javascript文件(不要忘记将其包含在index.html中),然后声明您的全局变量,该变量将在您的所有Web解决方案中提供。
<强> globals.js: 强>
var _i = 0; // Would not recomend using "i" as the variable name since it
// can polute the global scope
<强> yourFile.js: 强>
function mul()
{
var qty = document.getElementsByClassName("qty");
var rs = document.getElementsByClassName("rs");
var amt = document.getElementsByClassName("amt");
var mul=(qty[_i].value)*(rs[_i].value);
amt[_i].setAttribute("value",mul);
sp.appendChild(iteminp);
sp.appendChild(qtyinp);
sp.appendChild(rsinp);
sp.appendChild(amtinp);
_i++;
}
答案 1 :(得分:1)
JS变量是函数的本地变量,或者它们是全局变量。由于您在函数外部声明了i
,因此它是全局的。
要证明这一点,请将其另存为test.html,在浏览器中打开并按几次按钮。我简化了你的功能!
<script>
var i=0
function mul(){
alert("i: " + i++)
}
</script>
<button onclick='mul()'>Press me</button>
答案 2 :(得分:1)
您可以创建一个装饰器函数,该函数可以使用计数器包装您的函数,该计数器将允许您通过只读属性访问计数。
由于使用了Symbol
,此解决方案将需要现代浏览器,但您可以用dunder属性替换它,例如。 __count__
在它的位置。
// this is used to create a privaty property on your function
const COUNT = typeof Symbol !== 'undefined' ? Symbol('count') : '__count__'
// this function takes your function and wraps it with a counter
function counter(fn) {
// this is called whenever you call the decorated function
function _counter(...args) {
// increment the counter
_counter[COUNT]++
// call the original function
return fn(...args)
}
// create the private property on your function and the accessor
Object.defineProperties(_counter, {
[COUNT]: { value: 0, writable: true },
name: { value: fn.name || 'counter' },
count: { get: () => _counter[COUNT] }
})
// return the decorator function
return _counter
}
// function to decorate
function _mul(x, y) {
// do something to multiply
return x * y
}
// decorate your functions with the counter
const mul = counter(_mul)
const mul2 = counter(_mul)
// proof that both counters are independent and work correctly
console.log(
mul(1, 2), // 2
mul(3, 4), // 12
`mul has been called ${mul.count} times`
)
console.log(
mul2(5, 6), // 30
mul2(7, 8), // 56
mul2(9, 10),// 90
`mul2 has been called ${mul2.count} times`
)
&#13;
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
&#13;