如何检测 JavaScript 中的非系统变量?

How to detect non-system-variables in JavaScript?

如何检测用户定义的 'window' 的所有子项?

我想检测window.test,但我不想检测window.Math。 有没有办法列出这些变量?

您的问题很有趣,但没有显示出任何研究成果。我建议您添加更多信息。它可能对面临同样问题的更多读者有用...


加载网页时,您会得到一个全新的 window 对象。因此,如果您想检测自定义属性,最好将 window 的初始状态存储在代码的顶层。它将允许您稍后使用 Object.getOwnPropertyNames()Object.keys().

检索新属性

Object.getOwnPropertyNames()

var customKeys,
    // We save the initial length of the array containing window properties
    nbProps = Object.getOwnPropertyNames(window).length;
 
    // Custom properties
    window.foo = 'Foo';
    window.bar = 'Bar';

    // We get the latest properties that were internally pushed to the array
    customKeys = Object.getOwnPropertyNames(window).slice(nbProps);
    
    console.log(customKeys);

Object.keys()

var customKeys,
    // We save the initial length of the array containing window properties
    nbProps = Object.keys(window).length;
 
    // Custom properties
    window.foo = 'Foo';
    window.bar = 'Bar';

    // We get the latest properties that were internally pushed to the array
    customKeys = Object.keys(window).slice(nbProps);
    
    console.log(customKeys);

Object.getOwnPropertyNames() 对比 Object.keys()

Object.getOwnPropertyNames()Object.keys()的区别是可枚举性Object.getOwnPropertyNames() 考虑了对象的所有属性,包括不可枚举的属性,而 Object.keys() 只考虑了可枚举的属性。

看下面代码:

console.log('Object.getOwnPropertyNames(window)');
console.log(Object.getOwnPropertyNames(window).length + ' properties');
console.log('Math? ' + Object.getOwnPropertyNames(window).includes('Math'));

console.log('Object.keys(window)');
console.log(Object.keys(window).length + ' properties');
console.log('Math? ' + Object.keys(window).includes('Math'));