我通过分割字符串得到一组像下面这样的值
var values = [ "Budget1-green","Team1-green","Risk1-green","Benefit1-green","Scope1-green","Schedule1-green" ];
我希望能够将 – 之后的值存储在如下变量中.有关如何使用javascript或jQuery执行此操作的任何想法?
var Budget1 = 'green'; var Team1 = 'green'; var Risk1 = 'green'; var Benefit1 = 'green'; var Scope1 = 'green'; var Schedule1 = 'green';
解决方法
试试这个
它循环遍历数组中的每个元素,将其拆分并将其存储为对象.之后您可以像这样调用这些值
objVariables["Budget1"] // returns green
var values = ["Budget1-green","Schedule1-green"]; var objVariables = {}; for(var x=0;x<values.length;x++){ var splitted = values[x].split("-"); objVariables[splitted[0]] = splitted[1]; } console.log(objVariables); // Calling each variables // They all will return green since it is the data you have given console.log(objVariables["Budget1"]); console.log(objVariables["Team1"]); console.log(objVariables["Risk1"]); console.log(objVariables["Benefit1"]); console.log(objVariables["Scope1"]);