Javascript arguments 测试

如下测试代码所展示, arguments 与 方法参数 的对应变化行为,没有任何javascript的语法定义可遵循,你无法通过参数按值传递或其他基础语言规则推导出该行为。

但是利用arguments,却可以实现很多有用的功能,具体例子可以参考MDN上关于该关键字的说明。

!function(a, b, c, d, e) {
    a = 4;
    console.log("After set a = 4, arguments[0] is", arguments[0]);

    a = undefined;
    console.log("After set a = undefined, arguments[0] is", arguments[0]);

    a = 4;
    console.log("After set a = 4 again, arguments[0] is", arguments[0]);

    arguments[1] = 5;
    console.log("After set arguments[1] = 5, b is", b);

    arguments[1] = undefined;
    console.log("After set arguments[1] = undefined, b is", b);

    arguments[1] = 5;
    console.log("After set arguments[1] = 5 again, b is", b);

    delete arguments[2];
    console.log("After delete arguments[2], c is", c);
    arguments[2] = 6;
    console.log("After set arguments[2] = 6, c is", c);

    arguments[3] = 7;
    console.log("After change arguments[3] from undfined to 7, d is", d);

    e = 8;
    console.log("After change e from undfined to 8, arguments[4]:", arguments[4]);
}(1, 2, 3);

// 结果如下
// After set a = 4, arguments[0] is 4
// After set a = undefined, arguments[0] is undefined
// After set a = 4 again, arguments[0] is 4
// After set arguments[1] = 5, b is 5
// After set arguments[1] = undefined, b is undefined
// After set arguments[1] = 5 again, b is 5
// After delete arguments[2], c is 3
// After set arguments[2] = 6, c is 3
// After change arguments[3] from undfined to 7, d is undefined
// After change e from undfined to 8, arguments[4]: undefined

你可能感兴趣的:(JavaScript)