繁体   English   中英

Javascript 对象将变量理解为字符串而不是变量

[英]Javascript objects understand a variable as string instead of a variable

我有两个关于 javascript 和对象的问题。 第一个是:

我有这部分代码:

  const handleAnotherStep = () => {
    let procedures = 
      {key:
        {
          stepType: {
            stepCode: {
              language: stepText,
              timeout,
              nextInstruction,
            }
          }
        }
      }
    setProcedures(procedures)
    console.log(procedures)
  }

键、stepType、stepCode、language、stepText、timeout 和 nextInstruction 在 useState() 中。 问题是:console.log 这个是:

[![在此处输入图像描述][1]][1]

但它应该是这样的:

[![在此处输入图像描述][2]][2]

你看? 应该写的是 stepType 变量的内容,而不是 s'tepType'。 而不是“钥匙”,钥匙的内容应该在那里。 你明白我的意思吗? 请帮助我,我在这方面很挣扎,我是 JS 的新手。 nextInstruction 和 timeout 工作得很好。 我认为 javascript 认为 key、stepType、stepCode 和 language 是一个字符串,而不是一个变量。

使用[var]获取变量的值作为键,对于值,您可以给出变量本身。

  const handleAnotherStep = () => {
    let procedures = 
      {[key]:
        {
          [stepType]: {
            [stepCode]: {
              [language]: stepText,
              timeout,
              nextInstruction,
            }
          }
        }
      }
    setProcedures(procedures)
    console.log(procedures)
  }

对于您的第二个问题,添加一种方法来处理您不需要检查的步骤的添加,因为您只想添加一个 object 所以我认为您可以简单地给出,

  const handleAnotherStep = () => {
    let newProcedures = 
      {[key]:
        {
          [stepType]: {
            [stepCode]: {
              [language]: stepText,
              timeout,
              nextInstruction,
            }
          }
        }
      }
    setProcedures({...prevProcedures, ...newProcedures})
    console.log(procedures)
  }

注意:同样在设置 state 后立即记录程序不会给出正确的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM