简体   繁体   English

如何使用Javascript或jQuery将两个字符串连接成一个变量名?

[英]How can I concatenate two strings into a variable name with Javascript or jQuery?

This question has been asked before, I wanted to create a (possibly) simpler version for others to (maybe) understand easier. 之前曾有人问过这个问题,我想为他人创建一个(可能)更简单的版本,以便(也许)更容易理解。

What I wanted to do was combine a string with the data (string) from a variable to create a variable name. 我想要做的是将字符串与变量中的数据(字符串)结合起来以创建变量名称。 I suppose it would be called a dynamic variable? 我想它会被称为动态变量吗?

In this example I want to add a class and text to a div.. 在此示例中,我想向div添加一个类和文本。

<div class="time fa"></div>

..based on changing data which I get from a json file. ..基于更改从json文件中获取的数据。

var timetain = 10;
var timebus = 20;
var icontrain = 'fa-train';
var iconbus = 'fa-bus';
var type = 'bus'; // this string comes from a json file, it will either be train or bus

So I want to add the word time to the data from the variable named type to output the data from either timetrain or timebus 所以我想在名为type的变量中向数据添加time一词,以输出来自timetraintimebus的数据

$('.time').text('Travel by bus will take |'time'|+|type| minutes');
$('.time').addClass(|'icon'|+|type|));

I suppose another way of wording the question would be "How to combine a variable's data with a string to get the data from a third variable with Javascript?" 我猜想问题的另一种表达方式是“如何将变量的数据与字符串结合起来,以使用Javascript从第三个变量中获取数据?”

Why not make an associative array of the times? 为什么不对时间进行关联排列?

time = {'bus': 20, 'train': 10}

etc.? 等等。? Than just access it with time[type] . 比只是使用time[type]访问它。 This is much safer than what you want to do (you would have to rely on eval), which seems like overkill for this. 这比您想做的事要安全得多(您必须依靠评估),这似乎有些过头了。

Using ES6 template literals : 使用ES6 模板文字

 var time = "30", typesArr = ["bus", "train", "foot"], type = typesArr[ Math.random()*typesArr.length|0 ]; // pick random array item // mix values with strings: document.write( `Travel by ${type} will take ${time} minutes` ); 

Basically you cannot construct a variable name in javascript, unless it is an Object's Key, so you have to store the keys in some object in order to access them, but in your case it's much easier: 基本上,您不能在javascript中构造变量名,除非它是对象的键,所以您必须将键存储在某个对象中才能访问它们,但在您的情况下,这要容易得多:

$('.time').addClass('icon fa-' + type); // example => 'icon fa-train'

But if you really wanted to construct the keys dynamically you could do: 但是,如果您真的想动态构造键,则可以执行以下操作:

var types = {
    train : "fa-train",
    bus : "fa-bus"
};

var whatever = "bus";
var type = types[whatever];  // "fa-bus"

Nicht so @Hastig, lieber ordentlich machen. Nicht所以@Hastig,lieber ordentlich machen。

A better solution without using Eval: 不使用Eval的更好解决方案:

Most programming languages nowadays support a data-structure to "group" variables that belong together. 如今,大多数编程语言都支持一种数据结构,以将属于在一起的变量“分组”。 It's called an Object. 它称为对象。 I can't come up with a single disadvantage in using Objects over multiple variables. 在多个变量上使用对象时,我无法提出一个缺点。 This approach is even (a teeny tiny bit) faster than your attempt with eval() . 这种方法甚至比您使用eval()尝试还要快(很少eval()

 var configByType = { "train": { label: "train", time: 10, icon: "fa-train" }, "bus": { label: "bus", time: 20, icon: "fa-bus" } } function travel(type){ //because creating and adding a new `span` is simpler //than checking wich classes to remove on `.time.fa` var $span = $('.time').html('<span>').children(); if(type in configByType){ let config = configByType[type]; $span.addClass(config.icon) .text('Travel by '+ config.label +' will take ' + config.time + ' minutes') }else{ $span.text('unsupported type: ' + type); } } $('#update').click(function(){ var types = ["car", "bus", "train", "plane"]; var randomType = types[Math.floor(Math.random() * types.length)]; travel(randomType) }); travel('bus'); 
 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="time fa"></div> <br> <input id="update" type="button" value="update" /> 

A Solution Using Eval 使用评估的解决方案

eval('string' + variableName)

Applied To Provided Code 应用于提供的代码

 var timetain = 10; var timebus = 20; var icontrain = 'fa-train'; var iconbus = 'fa-bus'; var type = 'bus'; // this data (string) comes from a json file, it will either be train or bus $('.time').text('Travel by bus will take ' + eval('time' + type) + ' minutes'); $('.time').addClass(eval('icon' + type)); 
 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="time fa"></div> 

Note 注意

Before using this solution be sure to read more about the criticisms of using eval 在使用此解决方案之前,请务必阅读有关使用eval批评的更多信息

This solution works and addresses the question as asked. 此解决方案有效并按要求解决了问题。 I assume the downvotes are because of the criticisms that I pointed out and that there are better ways to go about things if properly planned but we'll never know because nobody cared to explain themselves. 我认为投票否决的原因是我指出的批评,而且如果计划周密,还有更好的方法来解决问题,但是我们永远不会知道,因为没人愿意自我解释。

I needed the simple eval way because I was putting together a complicated web of different json file comparisons for a simple game app and needed a quick and easy 'variable-variable', php-style method as placeholder code until I was able to better think everything through. 我需要一种简单的评估方法,因为我将一个简单的游戏应用程序组成了一个复杂的网络,将不同的json文件进行比较,并且需要一种快速,轻松的“可变变量”,php样式的方法作为占位符代码,直到我能够更好地思考一切都通过。

In the more advanced versions I am using objects and arrays like recommended in the other answers here but I was unable to think through things without using eval as temporary 'scaffolding'. 在更高级的版本中,我正在使用对象和数组,如此处其他答案中所建议的那样,但是如果不将eval用作临时的“脚手架”,就无法思考问题。

Fiddle 小提琴

https://jsfiddle.net/Hastig/o169ja8w/ https://jsfiddle.net/Hastig/o169ja8w/

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

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