在循环中发出问题,在javascript中执行一次

时间:2018-02-08 07:08:56

标签: javascript arrays scilab

我有这个代码,结果应该是[0,1,2,3,0,3],但我只得到[0,1,2,3]作为输出,因为循环只会发生一次。< / p>

frequ=[[1],[3]]
ppcm=3
den=1
frd1=[[1],[3]]
offset=[ [ 0 ], [ 0 ] ]

for (i = 0; i < frequ.length-1; i++) {

      var matind1 = offset[i] * den;
      var matind2 = frd1[i][0];
      var matind3 = parseFloat(ppcm);
      var mat1 = matindices(offset[i] * den, frd1[i][0], parseFloat(ppcm));
}

    console.log(mat1);

    function matindices(from, diff, to) {
      //fucntion which implements range list of scilab like matindices[1:2:10] gives 1.    3.    5.    7.    9.
      //which was not possible in js so made function
      var arrayind = [];
      for (i = 0; i <= to; i++) {
        arrayind.push(i);
        i = i + diff - 1;
        if (i >= to) {
          return arrayind;
        }
      }


}

2 个答案:

答案 0 :(得分:0)

您的i变量未定义,因为该变量和其他函数也使用相同的变量。试试这个,

frequ=[[1],[3]]
ppcm=3
den=1
frd1=[[1],[3]]
offset=[ [ 0 ], [ 0 ] ]

for (var j = 0; j < frequ.length; j++) {

      var matind1 = offset[j] * den;
      var matind2 = frd1[j][0];
      var matind3 = parseFloat(ppcm);
      var mat1 = matindices(offset[j] * den, frd1[j][0], parseFloat(ppcm));
  console.log(mat1);
}

    console.log(mat1);

    function matindices(from, diff, to) {
      //fucntion which implements range list of scilab like matindices[1:2:10] gives 1.    3.    5.    7.    9.
      //which was not possible in js so made function
      var arrayind = [];
      for (var i = 0; i <= to; i++) {
        arrayind.push(i);
        i = i + diff - 1;
        if (i >= to) {
          return arrayind;
        }
      }
}

这将输出,

[0, 1, 2, 3]
[0, 3]

此代码符合您的要求,

frequ=[[1],[3]]
ppcm=3
den=1
frd1=[[1],[3]]
offset=[ [ 0 ], [ 0 ] ]

var mat1 = [];
for (var j = 0; j < frequ.length; j++) {

      var matind1 = offset[j] * den;
      var matind2 = frd1[j][0];
      var matind3 = parseFloat(ppcm);
      mat1.push.apply(mat1, matindices(offset[j] * den, frd1[j][0], parseFloat(ppcm)));
  //console.log(mat1);
}

    console.log(mat1);

    function matindices(from, diff, to) {
      //fucntion which implements range list of scilab like matindices[1:2:10] gives 1.    3.    5.    7.    9.
      //which was not possible in js so made function
      var arrayind = [];
      for (i = 0; i <= to; i++) {
        arrayind.push(i);
        i = i + diff - 1;
        if (i >= to) {
          return arrayind;
        }
      }


}

答案 1 :(得分:0)

您可以采用简化的for循环,以from开头,并将diff作为增量值。

在函数结束时返回数组,而不检查for循环内部。

您需要在使用范围内声明所有变量,以及在使用相同命名变量i的函数中,它可能会与全局变量发生冲突。

未声明的变量在Javascript中首次使用时声明为全局变量。

function matindices(from, diff, to) {
    var arrayind = [], i;
    for (i = from; i <= to; i += diff) {
        arrayind.push(i);
    }
    return arrayind;
}

var frequ = [[1], [3]],
    ppcm = 3,
    den = 1,
    offset = [[0], [0]],
    i;
    
for (i = 0; i < frequ.length; i++) {
    console.log(matindices(offset[i][0] * den, frequ[i][0], ppcm));
}