gpt4 book ai didi

javascript - 使用 JavaScript 获取所有对象(DOM 或其他)

转载 作者:数据小太阳 更新时间:2023-10-29 05:53:09 25 4
gpt4 key购买 nike

简短版:

  • 如何获得所有对象的列表(包括它们的后代 对象)在页面上(不仅仅是第一深度对象)?
    • 预期的子问题:我如何跟踪 当我走过物体时访问过的物体?

提前致谢。



长版(带背景!!):

使用in 关键字我们可以获得一个对象的所有属性。 (并且使用 hasOwnProperty 方法允许我们只过滤掉属于该对象的属性,而不是继承的属性。)

for (var prop in obj) {
if (typeof(obj[prop]) == 'object' && obj.hasOwnProperty(prop)) {
showObjectsOfInternal(obj[prop], visitedObjects); // recursion.
}
}

这是一个很好的起点,但我想获取所有对象。可以想象遍历所有属性并累积对象,然后递归地遍历这些对象。然而,如果有一个对象引用循环,比如一个引用自身的对象,比如在 window.window 中,最好不要陷入其中。因此需要一种方法来在递归期间跟踪所有“访问过的对象”。

要跟踪被访问的对象,确实需要一个基于对象内部对象键的对象哈希集。我通过制作一个 visitedObjects 对象并将其键设置为要添加的对象来尝试这样做,而值并不重要。

if(visitedObjects[obj] == 1){return;}
visitedObjects[obj] = 1;

但这对我不起作用。 (它似乎将对象变成了键的字符串,而不是使用它们的内部引用键)

所以我决定改用数组并添加 indexOf 方法。

Array.prototype.indexOf = function(obj){
for(var i = 0; i < this.length; i++)
{
if(this[i] == obj) // reference comparison for non-primitive objects.
{
return i;
}
}
return -1;
}

但这也不起作用(最终我发现我无法执行 for(var prop in obj) 即使对象不为空!调试器说 obj 没有支持该属性。)

无论如何,这是我的错误代码:

function showObjectsOf(obj) {
var objHolder = new Array();
var ancestorNames = new Array();
ancestorNames.push('obj');
showObjectsOfInternal(obj, objHolder, ancestorNames);
}
function showObjectsOfInternal(obj, visitedObjects, ancestorNames) {
if (visitedObjects.indexOf(obj) != -1) {
return;
}
visitedObjects.push(obj);
alert(getAncestorString(ancestorNames));
for (var prop in obj) {
if (typeof (obj[prop]) == 'object') {
ancestorNames.push(prop);
showObjectsOfInternal(obj[prop], visitedObjects, ancestorNames);
ancestorNames.remove(prop);
}
}
}
function getAncestorString(ancestorNames) {
return ancestorNames.join('.');
}

Array.prototype.indexOf = function(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] == obj) {
return i;
}
}
return -1;
}
Array.prototype.remove = function(obj){
var ind = this.indexOf(obj);
if(ind != -1)
{
this.splice(ind,1);
}
}
window.onload = function() { showObjectsOf(window); };

更新实际上,字典可能是更好的方法。它在 IE 中对我不起作用。不过在 chrome 中工作正常。

最佳答案

我的快速尝试:

var objs = []; // we'll store the object references in this array

function walkTheObject( obj ) {
var keys = Object.keys( obj ); // get all own property names of the object

keys.forEach( function ( key ) {
var value = obj[ key ]; // get property value

// if the property value is an object...
if ( value && typeof value === 'object' ) {

// if we don't have this reference...
if ( objs.indexOf( value ) < 0 ) {
objs.push( value ); // store the reference
walkTheObject( value ); // traverse all its own properties
}

}
});
}

walkTheObject( this ); // start with the global object

关于javascript - 使用 JavaScript 获取所有对象(DOM 或其他),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8409577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com