如何将数组拆分为多个数组,每个数组都有唯一的名称 [英] How to split an array into multple arrays each with a unique name

查看:296
本文介绍了如何将数组拆分为多个数组,每个数组都有唯一的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组= [A,1,0,1,0,1,B,1,0,0,1,A,1]
我需要将此数组拆分为多个数组。分割将出现在A或B位置,如下面的新阵列所示。新数组的名称使用字符串group加上从1或0开始的递增数字。
最终结果应该如下所示:

  group1 = [A,1,0,1,0,1] 
group2 = [B,1,0,0,1]
group3 = [A,1]

我可以通过创建一个数组(arrTemp)来获得我需要的数组部分,所以我可以(A,1,0,1,0,1),(A,1,0,0,1)和(A,1)的区段(索引) 。但我不知道如何将数组的slice()的结果存储在数组中,其唯一名称加1。
这是我到目前为止所尝试的结果:

  var arr = [A,1,0,1,0,1,B,1,0,0,1,A,1]; 
arr.forEach(myFunction)
function myFunction(item,index){
if((item ==A)||(item ==B)){
arrTemp.push(index);
arrTemp = arrTemp; //不知道我需要这个。 (var i = 0; i< arr.length; i ++){
sectArray = arr.slice();我做了这个,所以它的数组将会是全局
}
}
arrTemp [i] + 1,arrTemp [i + 1])$ ​​b $ b'group'+ [i] = [arrTemp [i],sectArray]; //这里是我的问题。


解决方案

好像你是试图动态地创建变量。这似乎很棘手,可能无法正常工作。你应该可能得到的是一些结果集合。例如:

var containerArray = [];



然后:

 <$ c $ arg.slice(arrTemp [i] + 1,arrTemp [i + 1])$ ​​b $ b containerArray [$ c> for(var i = 0; i< arr.length; i ++){
sectArray = arr.slice [ i] = [arrTemp [i],sectArray];

现在 containerArray 会拥有你所有的东西。你也可以用一个对象来做到这一点:

var containerObject = {};



之后是同样的东西。


I have an array = [A,1,0,1,0,1,B,1,0,0,1,A,1] I need to split this array into multiple arrays. The split will occur at the "A" or "B" position as seen in the new arrays below. The names of the new arrays use the string "group" plus an incremented number starting with 1 or 0. The end result should look like:

group1 = [A,1,0,1,0,1]
group2 = [B,1,0,0,1]
group3 = [A,1]

I can get the section of the array I need by creating an array (arrTemp), so I can store the positions (indexes) and later use slice() to get the sections I want (A,1,0,1,0,1), (A,1,0,0,1), and (A,1). But I don't know how to store the results of my slice()'s in arrays with unique names incremented by 1. This is what I have tried so far:

var arr = [A,1,0,1,0,1,B,1,0,0,1,A,1];
arr.forEach(myFunction)
function myFunction(item, index)    {
if ((item=="A") || (item=="B")) {
arrTemp.push(index);
arrTemp=arrTemp; //not sure I need this. I did this so it array would be global
}
}
for (var i = 0; i < arr.length; i++){
sectArray = arr.slice(arrTemp[i]+1,arrTemp[i + 1])
'group' + [i] = [arrTemp[i],sectArray]; //here is my problem.
}

解决方案

It seems like you're trying to dynamically create variables. That seems tricky and probably won't work. What you should probably have is some collection of results. Probably a parent array that holds all of them.

For example:

var containerArray = [];

Then:

for (var i = 0; i < arr.length; i++){
    sectArray = arr.slice(arrTemp[i]+1,arrTemp[i + 1])
    containerArray[i] = [arrTemp[i],sectArray];
}

Now containerArray will have all of your stuff. You can also do this with an object:

var containerObject = {};

And the same thing after.

这篇关于如何将数组拆分为多个数组,每个数组都有唯一的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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