如何根据从字符串中提取的名称在运行时创建变量? [英] How can I create variables at run-time based on names pulled from a string?

查看:195
本文介绍了如何根据从字符串中提取的名称在运行时创建变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人可以协助并希望在JavaScript中可以实现这一点。我的格式基本上有以下字符串:

Hoping someone can assist and hoping this is possible in JavaScript. I basically have the following string in the format:

A,B,C:D,E,F

A,B,C:D,E,F

我想要实现的是将左侧JavaScript变量配对到:左侧的方法,右侧右侧值为:

What I am trying to achieve is a means of pairing up left hand side JavaScript variable, to the left of the ":" with the right hand side values to the right of the ":"

我基本上希望设置以下变量,以便我可以在我的编码中使用,即:

I basically would like to have the following variables set in , so that I can use in my coding, i.e:

var A = D;
var B = E;
var C = F;

然后我可以使用A,B和C的值作为其他JavaScript函数的参数。

I can then use the values of A,B and C as parameters into other JavaScript functions.

我已经看过这个字符串操作的分割和切片方法,但不确定如何将左手边与右边的值配对。

I have looked at the split and slice methods for this string manipulation but unsure how to pair up left hand side with right hand side values.

任何帮助都会很棒,谢谢!

Any help would be great, thanks!

推荐答案

使用此方法(将变量附加到对象),您可以在没有eval语句的情况下引用代码中的变量。

With this method (attaching variables to an object), you can reference variables in code without an eval statement.

a = "A,B,C:D,E,F";
array = a.split(":"); //split on the colon, get two strings
lefts = array[0];
rights = array[1];

obj = {} //object to attach variables to.
for( var i = 0; i < lefts.length; i++ )
{
  obj[lefts[i]] = rights[i]; //set the member variables of obj
}

obj.A // D
obj.B // E
obj.C // F

如果您关心浪费的逗号属性,请在设置之前检查lefts [i]是否等于逗号对象。

If you care about the wasted comma property, check if lefts[i] is equal to a comma before you set on the object.

这篇关于如何根据从字符串中提取的名称在运行时创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆