如何根据参数的值打印出不同的结果?
How do I print out a different result based on value of a parameter?
我想知道您是否可以使用字符串连接来调用变量,甚至名称变量。我正在尝试根据函数中传递的参数输出不同的文本。
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不是数组。
相关文章:
- 奇怪的Javascript结果
- Javascript(jQuery)给了我奇怪的结果
- JSONP请求返回结果,但也触发error_callback
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- Javascript,输出结果后页面不断刷新
- 这是使用html快照和谷歌获取的预期结果吗?SEO/SPA
- 将地理编码结果转换为php变量以发布到mysql数据库
- AngularJS/HTML/Bootstrap元素用于动态搜索结果
- JQuery:向多个匹配结果添加换行符的最简单方法
- 指令的模板必须只有一个根元素:With restrict E&替换true
- 当查询不在displayField中时,引导Ajax Typeahead不显示结果
- webpack代码拆分了handlerbs文件——结果是文件很大
- JavaScript循环无法正确计算/显示结果
- Jquery移除或更改JSON根元素
- 相同的RegExp返回不同的结果-第一次是正确的结果,第二次是null
- 如何检测负责网站某些部分的JavaScript根文件
- Node.js使用Series函数(模式?)实现流控制时出现意外结果
- 试图将onChange函数作为道具传递给GrandChlidren,结果是TypeError:这是未定义的
- 没有根和跨域,无法使JSON正确读取
- jQuery使用api获取typeform结果