0

我有以下代码片段,其中 for 循环内部没有分配要包含的值,这是将数组复制到其他的正确方法吗??

就像这里

  var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
  var groupParam =    "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";



  var grpNameArr = groupParam.split("#");
  var groupcn= groupCondition.split("&");
  var m=grpNameArr.length;

var contain=new Array();
var cmds=new Array();
var ii;

for(ii=0;ii<(m-1);ii++)
{
   contain[ii] = groupCn[ii];
   cmds[ii] = grpNameArr[ii];
 }
4

5 回答 5

0

如果要克隆数组,可以使用本页中提到的 slice() 方法:

http://www.hardcode.nl/subcategory_1/article_414-copy-or-clone-javascript-array-object

var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
于 2013-01-24T09:22:04.647 回答
0

你的数组声明是错误的,应该是这样的: -

var groupcn=["All","All","All","All"]; 
var grpNameArr=["abc","def","ghi"]; 
于 2013-01-24T09:23:15.723 回答
0

So, after your edit, I see your problem was that you has some typo's in your variable names.

Replace:

var grpNameArr = groupParm.split("#");
var groupcn= groupCondtn.split("&");

With:

var grpNameArr = groupParam.split("#");
//                      ^ Missing `a` and `r`.
var groupCn= groupCondition.split("&");
//       ^ Capital C  ^ Missing `i`'s and `o`.

Old Answer

These 2 lines:

var groupcn = All,All,All,All; 
var grpNameArr = abc,def,ghi;

Are probably your problem.

What you're doing there is assigning the variable All to a new variable groupcn, then declaring All as a new variable, 3 times.

var groupcn=All,
    All, // new variable with the name `All`
    All, // new variable with the name `All`
    All; // new variable with the name `All`. These 3 override `All`

You'll need to initialize them like this:

var groupcn = [All,All,All,All]; 
var grpNameArr = [abc,def,ghi];

Other than that, assuming m is the length of groupcn, the code should work.

However, a shorter solution is to copy the arrays like this:

var contain = groupcn.slice();
var cmds = grpNameArr.slice();
于 2013-01-24T09:23:47.347 回答
0

you can use :

var contain=groupcn.concat();
var cmds=grpNameArray.concat();
于 2013-01-24T09:23:56.813 回答
-1

代码中有以下错误

  1. 对两个数组使用一个循环。由于长度不同,应该使用两个不同的循环。

  2. groupcn 变量中存在拼写错误。

检查此代码

<!DOCTYPE html>
<html>
<script>
function chk()
{
  var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
  var groupParam =    "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";



var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");

var contain=new Array();
var cmds=new Array();
var ii;

for(ii=0;ii<(groupcn.length-1);ii++)
contain[ii] = groupcn[ii];

for(ii=0;ii<(grpNameArr.length-1);ii++)
cmds[ii] = grpNameArr[ii];

alert("groupcn   =  "+contain);
alert("grpNameArr   =  "+cmds);
}
</script>
<body onload="chk()">

</body>
于 2013-01-24T09:30:32.237 回答