Javascript 检查零值参数

标签 javascript

我正在编写一个函数来检查参数是否为零,但它似乎无法正常工作。注意:使用 Chrome 作为我的浏览器,但是这段代码应该是跨浏览器支持的。

// check all arguments, and make sure they aren't zero

function zeroCheck(arg1, arg2) {
    var i, argsLen = arguments.length;
    for (i = 0; i <= argsLen; i += 1) {
        if (arguments[i] === 0) {
            // This is where it doesn't behave as I expected
            arguments[i] = 1; // make arg1 = 1
        }
    }
    console.log(arg1); // arg1 = 0
}

zeroCheck(0, 2);

我期望 arg1 等于 1,但它仍然等于 0

最佳答案

来自 ECMA-262 规范:

"For non-strict mode functions the array index (defined in 15.4) named data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function’s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object‘s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values."

但是如果你阅读了关于如何设置 arguments 对象的技术细节,我想你会发现它是基于调用函数时实际传递给函数的参数数量,而不是如何声明了许多命名参数,因此使用 arguments 和循环来检查每个命名参数的值,如果它们没有全部传入,则可能无法正常工作。尽管在您的情况下,如果您专门针对0 它应该可以工作,因为未传递的参数将是 undefined 而不是 0

话虽如此,arguments 对象实际 的具体行为取决于浏览器。 Chrome 不遵循规范。

关于Javascript 检查零值参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12138519/

相关文章:

javascript - jQuery。将一个对象插入另一个对象

javascript - 如何全局定义套接字变量

javascript - Javascript 对象中的意外标识符

javascript - 在 React 中将文本放在 div 的底部

javascript - 如何使用 javascript、css 检测浏览器/设备?

javascript - 访问React中子组件的refs

javascript - 无法清除其他函数中调用的 inverval

javascript - 使用javascript拦截文件下载

javascript - 另一个网站/跨域上的元素的Xpath

php - 在向下滚动事件后执行 MySQL 查询