为什么我在使用 eval() 语句时得到未定义的值

问题描述 投票:0回答:1
var count = 0
class node{
            data;
            leftchild;
            rightchild;
            constructor(data){
                this.data = data;
            }
            addleftchild(value){
                this.leftchild = value
            }
            addrightchild(value){
                this.rightchild = value
            }
            ///getter
            get data(){
                return this.data;
            }

这是我使用的课程

function addnode(num){
            eval("let value = nod"+num+".data")
            console.log(value) 

当我调用这个函数时,我得到的所有输出是 tree.html:42 Uncaught ReferenceError: 值未定义 在添加节点 问题似乎是当我尝试记录值时它是未定义的

javascript class eval
1个回答
1
投票

Eval 代码的执行就像在块中一样(reference),所以这样

eval("let value = nod"+num+".data")
console.log(value) 

大致相同
{
   let value = nod5.data
}
console.log(value) // error because 'value' didn't survive the block

您可以通过分配给已存在的变量来解决此问题:

let value
eval("value = nod" + num + ".data")

或者将作业移到外部

eval

let value = eval("nod" + num + ".data")

当然,这个问题仍然悬而未决,首先你是否需要

eval
。我猜你在这里更需要一个数组,这样你就可以简单地使用
nod5
,而不是动态变量
nodes[5]

© www.soinside.com 2019 - 2024. All rights reserved.