我只能看到索引和值。不显示长度或被调用者等其他属性。如何隐藏 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();
这将打印 length
和 callee
属性。
关于javascript - 为什么我无法在 `length` 输出中看到参数对象的 `console.log` 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654095/