javascript - 为什么我无法在 `length` 输出中看到参数对象的 `console.log` 属性?

标签 javascript

我只能看到索引和值。不显示长度或被调用者等其他属性。如何隐藏 console.log() 的属性?以及如何查看所有属性?

例如:

function test(){
    console.log(arguments);
    console.log(arguments.length);
}

test(1,2,3,4,5);

输出为 { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }5

实际上参数中有 length 属性,但我在 console.log(arguments) 中看不到。

最佳答案

因为 arguments.length 属性是不可枚举的。

您可以在对象上定义属性并设置其 enumerable属性为 false,像这样

var obj = {};

Object.defineProperty(obj, "name", {
    "value": "a",
    enumerable: false
});

console.log(obj);
// {}

您可以使用 Object.prototype.propertyIsEnumerable 检查相同的内容函数,像这样

function testFunction() {
    console.log(arguments.propertyIsEnumerable("length"));
}

testFunction();

将打印false,因为arguments 特殊对象的length 属性不可枚举。

如果您想查看所有属性,请使用此 question 中提到的答案.基本上, Object.getOwnPropertyNames甚至可以枚举不可枚举的属性。所以,你可以像这样使用它

function testFunction() {
    Object.getOwnPropertyNames(arguments).forEach(function (currentProperty) {
        console.log(currentProperty, arguments[currentProperty]);
    });
}

testFunction();

这将打印 lengthcallee 属性。

关于javascript - 为什么我无法在 `length` 输出中看到参数对象的 `console.log` 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654095/

相关文章:

javascript - AngularJs2 'angular not defined' 启动指南后出现错误

javascript - numeric.js 是否有一种仅在需要时显示小数的格式?

javascript - 在 focusin 上将类(class)添加到父级

javascript - 使用jquery检查长度

javascript - 如果 "value"属性为 "type",如何设置 "number"属性

javascript - c# 和 javascript 之间的夏令时问题

javascript - 我的 javascript 代码在同一窗口中打开包含输入值的 url 有什么问题吗?

Javascript更新和访问函数外部的变量

javascript - 替换两个标记之间的 URL 中的 ID

javascript - 根据主键和外键组合两个数组