我有以下代码( HERE 是可编辑的示例-用法:在输入字段中输入并监视控制台):
function test(event)
{
let keys = Object.keys(event);
let keysOwnProp = Object.getOwnPropertyNames(event);
let keysForIn=[]; for(let k in event) { keysForIn.push(k); }
console.log('keysForIn',keysForIn);
console.log('keys',JSON.stringify(keys));
console.log('keysOwnProp',JSON.stringify(keysOwnProp));
}
<input oninput="test(event)" placeholder="type something">
问题:
keysForIn
中看到所有(?)事件字段/属性,但是在keys
和keysOwnProp
中却只有一个:isTrusted
? keysForIn
是否有替代方法(如果可以,请提供)?答案 0 :(得分:0)
Object.keys
和Object.getOwnPropertyNames
似乎提供了仅属于对象的属性,而for..in
循环也将给出继承的属性
document.getElementById('test').addEventListener('input', function(event) {
let keys = Object.keys(event);
let keysOwnProp = Object.getOwnPropertyNames(event);
// location is one of the property which we get on using for..in
console.log(event.hasOwnProperty('location'))
let keysForIn = [];
for (let k in event) {
keysForIn.push(k);
}
})
<input id="test">
答案 1 :(得分:0)
在这里我复制粘贴Grégory NEUT答案-看起来是最好的答案:
Object.keys(...)
返回对象的非符号可枚举属性的名称,但仅返回未继承的属性的名称。
For...in
迭代对象的非符号可枚举属性的名称,无论是否继承。
Object.getOwnPropertyNames(...)
返回所有非符号属性(是否可枚举)。
据我所知,for ... in
除了获得继承的属性外别无选择
function displayDetail(o) {
let keys = Object.keys(o);
console.log('Object.keys > ', keys);
let keysOwnProp = Object.getOwnPropertyNames(o);
console.log('getOwnPropertyNames > ', keysOwnProp);
const keysForIn = [];
for (let k in o) {
keysForIn.push(k);
}
console.log('for ... in > ', keysForIn);
}
/**
* The basic object
*/
const obj = {
own: 'A',
};
/**
* We add a non enumerable property to the object
*/
Object.defineProperty(obj, 'notEnumerable', {
enumerable: false,
value: 123,
});
/**
* We create a new object based on the first (it will inherit it's properties)
*/
const objWithInheritedProperties = Object.create(obj);
console.log('REGULAR OBJECT\n');
displayDetail(obj);
console.log('\n-----------\n');
console.log('OBJECT WITH INHERITANCE\n');
displayDetail(objWithInheritedProperties);