简体   繁体   English

在javascript中将用户输入字符串分配为新的变量名称

[英]Assign a user input string as a new variable name in javascript

I have a text field in which the user inputs some text. 我有一个文本字段,用户可以在其中输入一些文本。 I'd like to take the first word of that text and turn it into a global variable name for an object holding the rest of the string content. 我想使用该文本的第一个单词,然后将其转换为持有其余字符串内容的对象的全局变量名称。 More string content will be added to object later, so internal indexing inside the object is required. 稍后将更多字符串内容添加到对象,因此需要在对象内部进行内部索引。

var textInput = $('#inputText').val();
var splitString = textInput.split(" ");
var firstWord = splitString[0];

This is where I get stuck. 这就是我卡住的地方。 How please do I create a new object with the string referenced by firstWord as the object's reference? 如何用firstWord引用的字符串作为对象的引用创建一个新对象?

Many thanks in advance. 提前谢谢了。

I would try something like this: 我会尝试这样的事情:

globalUserObjects = {};

var textInput = $('#inputText').val();
var splitString = textInput.split(" ");
var firstWord = splitString[0];

globalUserObjects[firstWord] = {};

// Now later you can add stuff to it

globalUserObjects[firstWord]["firstName"] = "John";
globalUserObjects[firstWord]["lastName"] = "Smith";

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

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