gpt4 book ai didi

javascript - 通过名称作为字符串检查变量是否存在于本地范围内?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:11 25 4
gpt4 key购买 nike

我想查明在本地范围内是否存在一个以给定名称作为字符串的变量。有没有办法做这样的事情?:

var name = 'myVariable';

function test(myVariable) {

//CHECK HERE if there is a locally scoped variable with the same name
//as the value of 'name'

}

最佳答案

我将借鉴 Bandrami 的回答和我的评论,因为我相信这是完成您想要做的事情的唯一方法。是的,我知道我正在使用 eval,但我认为没有任何选择。

if (typeof eval(name) !== 'undefined' && typeof window[name] === 'undefined'){ 
// variable exists in this scope
}

关于javascript - 通过名称作为字符串检查变量是否存在于本地范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433668/

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