如何根据参数的值打印出不同的结果?

How do I print out a different result based on value of a parameter?

本文关键字:结果 何根 参数 打印      更新时间:2023-09-26

我想知道您是否可以使用字符串连接来调用变量,甚至名称变量。我正在尝试根据函数中传递的参数输出不同的文本。

function myFunction(direction) {
  var previousElement = "Previous Element";
  var nextElement = "Next Element";
  console.log(direction+Element);
  //I want it to print "Previous Element" or "Next Element" depending on what the direction is.
}
myFunction('previous');

最安全的方法是将说明包装为一个对象:

function myFunction(direction) {
    var element = {
        "previous": "Previous Element",
        "next": "Next Element"
    };
    return direction in element ? element[direction] : false;
}
myFunction('previous');
//I want it to print "Previous Element" or "Next Element" depending on what the direction is.

您最好使用对象来保存它,并使用变量来访问带有括号符号的属性。

var msgs = {
   "previous" : "Previous Element",
   "next" : "Next Element"
};
function myFunction(direction) {
  console.log(msgs[direction]);
}
myFunction('previous');

为了做到这一点,你将不得不使用eval或其他一些味道基本上做同样的事情。

function myFunction(direction) {
  var previousElement = "Previous Element";
  var nextElement = "Next Element";
  
  // Construct an actual call to previousElement or nextElement, not a string
  var variable = eval(direction + "Element");
  
  console.log(variable);
}
myFunction('previous');
//I want it to print "Previous Element" or "Next Element" depending on what the direction is.

这当然不是最安全或最聪明的做法,但这是你所要求的,并返回正确的结果。

在函数中使用console.log(direction + "Element")

  • 连接两个字符串。当你试图访问一个不存在的数组元素时,你写错了代码。

  • Direction不是数组。