NodeJS 如何替换eval函数?[副本]

qzwqbdag  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(151)

此问题已在此处有答案

Accessing an object property with a dynamically-computed name(19回答)
7天前关闭
这是我的密码

const v1 = 'bin';
const nvmProfix = 'NVM_';

console.log(process.env.NVM_BIN);
//it prints NVM_BIN=/Users/someone/.nvm/versions/node/v16.16.0/bin

const nvmBinVar = `process.env.NVM_${v1.toUpperCase()}`;
console.log(nvmBinVar);
//it prints process.env.NVM_BIN

const nvmBin = `${eval(nvmBinVar)}`;
console.log(process.env.NVM_BIN);
//it prints NVM_BIN=/Users/someone/.nvm/versions/node/v16.16.0/bin

如何替换eval()pls?

bihw5rsg

bihw5rsg1#

你就不能用括号表示吗?

const
  nvmProfix = 'NVM_',
  v1 = 'bin',
  nvmBin = `${nvmProfix}${v1.toUpperCase()}`;

// Prints NVM_BIN=~/.nvm/versions/node/v16.16.0/bin
console.log(process.env.NVM_BIN); // Static access

// Prints NVM_BIN=~/.nvm/versions/node/v16.16.0/bin
console.log(process.env[nvmBin]); // Dynamic access

相关问题