Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的数组返回测试时是空的?_Javascript_Arrays_Jestjs - Fatal编程技术网

Javascript 为什么我的数组返回测试时是空的?

Javascript 为什么我的数组返回测试时是空的?,javascript,arrays,jestjs,Javascript,Arrays,Jestjs,我在上编程语言课,本周我们将学习JavaScript。除此之外,我已经完成了所有测试: ● powers › generates sequences of powers properly expect(received).toEqual(expected) // deep equality - Expected - 3 + Received + 1 - Array [ - 1, - ] + Array []

我在上编程语言课,本周我们将学习JavaScript。除此之外,我已经完成了所有测试:

  ● powers › generates sequences of powers properly

    expect(received).toEqual(expected) // deep equality

    - Expected  - 3
    + Received  + 1

    - Array [
    -   1,
    - ]
    + Array []

      82 |     expect(generatorToArray(powers, 2, -5)).toEqual([]);
      83 |     expect(generatorToArray(powers, 7, 0)).toEqual([]);
    > 84 |     expect(generatorToArray(powers, 3, 1)).toEqual([1]);
         |                                            ^
      85 |     expect(generatorToArray(powers, 2, 63)).toEqual([1, 2, 4, 8, 16, 32]);
      86 |     expect(generatorToArray(powers, 2, 64)).toEqual([1, 2, 4, 8, 16, 32, 64]);
      87 |   });

      at Object.<anonymous> (h2.test.js:84:44)

  console.log h2.js:41
    []

  console.log h2.js:41
    []

  console.log h2.js:41
    [ 1 ]
generatorToArray是一个必须是这样的函数,并且您不能更改它吗?如果是这样,函数期望生成器(幂函数)将最后一个参数作为回调调用,并返回结果

也就是说,生成器应该生成结果-这就是回调的目的-为每个生成的部分结果调用回调。然后,generatorToArray函数将这些生成的部分结果收集到一个数组中

所以幂函数不应该创建自己的数组,它应该只调用带有每个部分结果的回调:

function powers(x, y, callback){
    let count = 0;
    while(Math.pow(x,count)<=y){
        callback(Math.pow(x,count));
        count+=1;
    }
}

您发布的函数不应该在这个测试用例中失败。powers3,1的计算结果为[1]。问题一定出在generatorToArray中你必须告诉我们什么是generatorToArray函数generatorToArray幂,3,1似乎是用3个参数调用的,但是你的幂函数被定义为只有2。哇!这就成功了。我从来没有想到过,我想我需要时不时地仔细检查一下测试函数。非常感谢你!
function generatorToArray(generator, ...args) {
  const result = [];
  generator(...args, (item) => result.push(item));
  return result;
}
function powers(x, y, callback){
    let count = 0;
    while(Math.pow(x,count)<=y){
        callback(Math.pow(x,count));
        count+=1;
    }
}