javascript – 拆分一组字符串并存储在动态变量中

前端之家收集整理的这篇文章主要介绍了javascript – 拆分一组字符串并存储在动态变量中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通过分割字符串得到一组像下面这样的值
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"]);
原文链接:https://www.f2er.com/js/149886.html

猜你在找的JavaScript相关文章