javascript将变量组合成数组

时间:2014-04-12 21:07:28

标签: javascript arrays

有人可以帮我解决这个问题。我有两个变量,用逗号分隔的单词。

var names = "Verwerkende industrie, Retail, Primaire producent, Out of home, Groothandel, Grondstof, Consument, Bewerkende industrie";
var numbers = "9, 3, 4, 2, 7, 9, 3, 2";

我想将它们组合成一个最终看起来像这样的数组

var combined = [
                ['Verwerkende industrie', 9], 
                ['Retail', 3], 
                ['Primaire producent', 4], 
                ['Out of home', 2], 
                ['Groothandel', 7], 
                ['Grondstof', 9], 
                ['Consument', 3], 
                ['Bewerkende industrie', 2]
            ];

4 个答案:

答案 0 :(得分:1)

这应该有效。

var names = "Verwerkende industrie, Retail, Primaire producent, Out of home, Groothandel, Grondstof, Consument, Bewerkende industrie";
var numbers = "9, 3, 4, 2, 7, 9, 3, 2";

names = names.split(',');
numbers = numbers.split(',');
var combined = [];
for(var i = 0; i < names.length; i++){
  combined.push([names[i], parseInt(numbers[i])]);
}

答案 1 :(得分:1)

var names = "Verwerkende industrie, Retail, Primaire producent, Out of home, Groothandel,      Grondstof, Consument, Bewerkende industrie";
var numbers = "9, 3, 4, 2, 7, 9, 3, 2";

var namesArray = names.split(","); //split the string at ','. split() returns an array of result
var numbersArray = numbers.split(",");

var resultArray = []; //array to hold result

//since the namesArray and numbersArray are the same length, you can use one for-loop
for (var i=0, len=namesArray.length; i < len; i++) {
  resultArray[i] = [namesArray[i], parseInt(numbersArray[i])];
}

答案 2 :(得分:0)

var names = "Verwerkende industrie, Retail, Primaire producent, Out of home, Groothandel, Grondstof, Consument, Bewerkende industrie";
var numbers = "9, 3, 4, 2, 7, 9, 3, 2";

function zip(arrays) {
    return arrays[0].map(function(_,i){
        return arrays.map(function(array){return array[i]})
    });
}

// paramert = array
zip([
 names.split(/,\s+/),
 numbers.split(/,\s+/).map(function (i) { return parseInt(i); })
]);

答案 3 :(得分:0)

不幸的是,JavaScript并没有“拉链”。功能,但你可以做同样的事情:

var namesArr = names.split(", ");
var numbersArr = numbers.split(", ").map(function (s) { return parseInt(s); });
var combined = [];
for (var i = 0; i < namesArr.length; i++)
{
    combined[i] = [namesArr[i], numbersArr[i]];
}