Javascript:替换 Eval() 和对象长度未定义的问题
这是我通过浏览器 dom 结构进行递归的精简函数。
(function () {
function displaydom (child, parent) {
if (parent) {parent = parent+".";}; // if there is no parent then child is the parent
var jsns = eval(parent+child); // Join parent + child and eval
for (var i in jsns){ // loop through dom object's attributes
if (typeof jsns[i] == "object") { // if attribute is an object then recurse through
// display output here
displaydom (String(i) /** next child **/, parent+child);
};
};
};
displaydom ('self', '');
})();
有几个 - 可能很简单 - 问题我无法开始工作(在 Chrome 中):
- 需要删除 eval()
- 我想将 for 循环更改为
for (var i=0 , len = jsns.length; i < len; i++) {};
因为它更快,但我不断获得 jsns '0' 或 'undefined' 的长度。
PS - 不要尝试按原样运行代码,除非您希望浏览器崩溃!
Here's my stripped down function for recursing through a browsers dom structure.
(function () {
function displaydom (child, parent) {
if (parent) {parent = parent+".";}; // if there is no parent then child is the parent
var jsns = eval(parent+child); // Join parent + child and eval
for (var i in jsns){ // loop through dom object's attributes
if (typeof jsns[i] == "object") { // if attribute is an object then recurse through
// display output here
displaydom (String(i) /** next child **/, parent+child);
};
};
};
displaydom ('self', '');
})();
There are a couple - probably simple - problems with it that I haven't been able to get to work (in Chrome):
- need to remove eval()
- I want to change the for loop to
for (var i=0, len = jsns.length; i < len; i++) {};
because it's faster but I keep getting length for jsns '0' or 'undefined'.
P.S - Don't try and run the code as is unless you want your browser to crash!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 方括号表示法
至于你的第二个问题……
1. `parent` is an empty string.
2. Strings don't have a `self` property
3. Therefore `"".self` is `undefined`
4. `undefined` has no properties, so it can't have a length property
你可以不要对不是数组(或类似数组的对象)的东西使用传统的 for 循环,而且大多数对象都不是。
Use square bracket notation
As for your second question…
1. `parent` is an empty string.
2. Strings don't have a `self` property
3. Therefore `"".self` is `undefined`
4. `undefined` has no properties, so it can't have a length property
… you can't use a tranditional for loop over something which isn't an Array (or an array-like object), and most objects are not.
要删除 eval,您可以使用方括号,正如 David 所说,
您无法更改循环,这是因为您无法以这种方式迭代对象的属性你提议。对象属性只能通过名称访问,它们不按数字索引。执行此操作的唯一方法是您当前使用的 for-in 循环。
To remove eval, you can use square brackets as David said,
You can't change the loop, this is because you can't iterate over an object's properties in the way you propose. Object properties can only be accessed by name, they aren't indexed numerically. The only way to do this is the for-in loop you're currently using.