如何从JavaScript的文件对象中获取所有键/参数/属性?

6

我正在JavaScript中从File对象获取密钥,但是我不知道为什么对象的方法不能使用。

我尝试了Object.keys()和Object.getOwnPropertyNames()。为什么这些方法不起作用?

这里是示例:

        var obj = {name:'my_name',id:1,value:'my_val'}
        const file = document.getElementById('fileToUpload').files[0];

        console.log('Object.keys(file)',Object.keys(file));
        //Array []
        console.log('Object.keys(obj)',Object.keys(obj));
        //Array [3]
        console.log('Object.getOwnPropertyNames(file)',Object.getOwnPropertyNames(file));
        //Array []
        console.log('Object.getOwnPropertyNames(obj)',Object.getOwnPropertyNames(obj));
        //Array [3]
        console.log('file.name',file.name);
        //name.type
        console.log('obj.name',obj.name);
        //my_name
        console.log('Object',file);
        //File {...}
        console.log('Object',obj);
        //Object {...}
        console.log('type',typeof file);
        //object
        console.log('type',typeof obj);
        //object
1个回答

3

Object.keys()Object.getOwnPropertyNames()仅返回自有属性,无论它们是否可枚举。在本例中,您要获取的属性属于其prototype。因此,这些方法不起作用。

您仍然可以通过执行以下操作获取其属性:

const attributes = [];
for (attribute in file) {
  attributes.push(attribute);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接