[英]How to populate an array with integers from a loop in javascript
I just signed up in codewars and I'm trying the first kata. 我刚刚注册了Codewar,正在尝试第一批产品。 This is the question: 这是问题:
Write a function to multiply a number (x) by a given number (y) a certain number of times (n). 编写一个函数,将数字(x)乘以给定的数字(y)一定次数(n)。 The results are to be returned in an array. 结果将以数组形式返回。 eg. 例如。 multiplyBy(2, 4, 6); multipliBy(2,4,6); The output is: [8, 32, 128, 512, 2048, 8192] 输出为:[8、32、128、512、2048、8192]
I believe my code is write, when I do console.log I get the array that the exercise is asking for, but it won't let me proceed. 我相信我的代码是写的,当我执行console.log时,我得到了练习所要求的数组,但它不会让我继续。 I'd appreciate some help, thanks! 谢谢您的帮助,谢谢!
var array = [];
function multiplyBy(x, y, n) {
while (x<2049){
var z = x*y*n;
var x = z;
array.push(z)
}
}
multiplyBy(2,2,2);
console.log(array);
return array;
You have a few things going on outside your function which make it only work one time. 您在函数之外发生了一些事情,这使其只能运行一次。 Make sure that you keep everything inside the function until the last return
确保将所有内容保留在函数中,直到最后一次return
function multiplyBy(x, y, n) {
var array = []; // var this inside your function
for (; n > 0; --n) { // the loop is only supposed to happen n times
x = x * y; // you can reuse this variable (x)
array.push(x);
}
return array; // return statement should be inside your function
}
// example of logging the returned value
console.log(multiplyBy(2, 4, 6)); // [8, 32, 128, 512, 2048, 8192]
Your while
loop also was hardcoded to x<2049
, but this isn't always the case as it depends on the n
parameter given to the function 您的while
循环也被硬编码为x<2049
,但这并非总是如此,因为它取决于为函数指定的n
参数
it won't let me proceed 它不会让我继续
There are 3 issues in the code you posted that probably prevent you from proceeding, 您发布的代码中有3个问题可能会阻止您继续进行操作,
return array
is probably throwing a syntax error because it's outside a function return array
可能抛出语法错误,因为它在函数外部 multiplyBy
several times appends the new values onto the end of the previous array 在您的代码中,多次调用multiplyBy
会将新值附加到上一个数组的末尾 2, 4, 6
but used 2, 2, 2
in your own code 他们可能测试你的功能对等的价值准则检查它正常工作,这是不正确的在你的功能,即你给的例子输入2, 4, 6
,但使用2, 2, 2
在你自己的代码 As a final note, try to get into the habbit of indenting your code, it'll save you headaches reading it later as it lets you quickly see where blocks begin and end 作为最后的提示,尝试进入缩进代码的习惯,这将使您免于以后阅读它的麻烦,因为它使您可以快速查看块的开始和结束位置
Your return
is outside the function. 您的return
不在函数范围内。 And all calls to multiplyBy
populate the same array. 并且所有对multiplyBy
的调用都会填充相同的数组。 And your logic is flawed. 而且您的逻辑有缺陷。
Probably, it should be 大概应该是
function multiplyBy(x, y, n) { var array = []; while (n--) array.push(x *= y) return array; } console.log(multiplyBy(2,4,6));
Or, in ECMAScript 6, 或者,在ECMAScript 6中,
var multiplyBy = (x, y, n) => Array(n).fill().map(a => x*=y);
ramove最后的return,必须在函数中使用它来返回某些内容,如果不使用该函数将返回undefined。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.