javascript - 有没有办法使用函数参数的值来声明变量

标签 javascript function variables

我需要使用通过函数发送的名称来声明变量 作为参数/参数

function CreateDroptable(npcName) {
    Droptable.npcName = new Droptable();
}

我想要做的是如果输入“CreateDroptable(goblin)” 它将创建变量“Droptable.goblin” 但它却将其声明为“Droptable.npcName”

有办法解决吗?

最佳答案

function CreateDroptable(npcName) {
    Droptable[npcName] = new Droptable();
}

应该可以解决问题。字符串/数组/括号表示法正是出于这个原因。 :)

编辑:

我注意到您提到相应地使用它:CreateDroptable(goblin),它不会按原样工作。它应该像这样使用:

CreateDroptable("goblin");

其中 goblin 是一个字符串,而不是一个变量。

关于javascript - 有没有办法使用函数参数的值来声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28572206/

相关文章:

c# - 什么是基于实例的成员

c++ - c变量在内存中的存储

javascript - jQuery Mobile 中的中心控制组

javascript - 如果我在输入类型文本中写东西,请选中复选框

c - 使用函数创建链接列表时出现问题

javascript - 为什么 fs.writeFileSync() 会抛出 "is not a function"错误?

javascript - 基本 "Get Variable Value"使用 GopherJS

javascript - Jasmine 测试在网络浏览器中测试 javascript 上传文件

javascript - DynamoDB API 时间点备份启用

php - 人们曾经使用过variable.php 文件吗?