【问题标题】:A problem with the output of a function in JavaScript [duplicate]JavaScript中函数输出的问题[重复]
【发布时间】:2019-06-24 14:01:14
【问题描述】:

我是 JavaScript 的初学者,我刚刚了解了函数和数组,但我对下面的代码有疑问: 首先我定义了下一个数组:

let WorkerS = {
    Php : "Alexander",
    Python : "Vadim",
    Html : "Vladimir",
    JS : "Fyodor",
};

然后我定义了这个简单的函数:

    const Element = (Language) => {
    return WorkerS.Language
};

当我打电话时:

console.log(Element(Php));

它给了我一个错误:

ReferenceError: Php is not defined

,请帮我知道错误在哪里:

【问题讨论】:

  • 你想要return WorkerS[Language];
  • 您还想为您的函数提供一个字符串,例如Element('Php')

标签: javascript arrays function object


【解决方案1】:

将您的功能更改为:

const Element = (Language) => {
  return WorkerS[Language];
};

然后将您的呼叫更改为

console.log(Element('Php')); //as you can see Php is a string

【讨论】:

  • 有没有办法直接输入:console.log(Element(Php)) 从函数内部把“Php”转成字符串?
  • 不,如果你只使用 Php,那么它必须是在 Element(Php) 调用之前声明的变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多