简体   繁体   中英

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?

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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