if I have a simple test function that adds even numbers to an array:
function isEven(n){
var enumbers = [];
if (n % 2 == 0){
enumbers.push (n);
}
}
how can I increment my parameter until I have a set number of members in my array? for instance, I've tried this:
function isEven(n){
var enumbers = [];
while ( enumbers.length < 10){
if (n % 2 == 0){
enumbers.push (n);
}
console.log (enumbers);
n = n + 1;
isEven(n);
}
}
isEven(1);
but it seems to just create a new array for each number until it finally throws a range error (maximum call stack size exceeded).
It's creating that array multiple times because you're constantly calling that function with:
isEven(n);
You're also not comparing to the length of the array, just the array. Add .length to enumbers. Try changing to:
var enumbers = [];
while ( enumbers.length < 10){
if (n % 2 == 0){
enumbers.push (n);
}
console.log (enumbers);
}
I'm not sure if I understood your question.
But you shouldn't use global variables, and it is unnecessary to call your function recursively inside a while loop.
The error maximum call stack size exceeded is your browser trying to break a infinity loop.
This is what you need.
Examples here jsFiddle1 and jsFiddle2
function isEven(n) {
var enumbers = [];
while (enumbers.length < 10) {
if (n % 2 == 0) {
enumbers.push(n);
}
n++;
}
return enumbers;
}
Setup a test
var n = 1;
var evenArray = isEven(n); //call isEven function and it returns an array
document.body.innerHTML = evenArray; //2,4,6,8,10,12,14,16,18,20
The problem is that (enumber < 10) apparently always evaluates to true, causing an endless loop. But it is this comparison that is wrong, since you're comparing an integer with an array I think you're trying to get the array length?:
while (enumbers.length < 10) {
Another thing. enumbers is a local variable, so each call to isEven has it's own array. Therefore, the functions is called recursively, over and over again.
I suggest you create the array outside of is even method
I would have written something like:
function isEven(n,enumbers){
while(enumbers < 10){
if (n % 2 == 0){
enumbers.push (n);
}
console.log (enumbers);
n = n + 1;
isEven(n, enumbers);
}
}
var enumbers = [];
isEven(1,enumbers);
Related
I'm 3 months into Javascript, and find it has no respect for its own declarations.
I have declared an empty array, and want to push a number to it, so that it returns an array of numbers (i.e., separable). However, I am told .push() is not a function. Concat() will not work either, and of course += ruins the algorithm.
How do I get it to accept each next value into an array?
I have tried using 'new Array()', but it does not assist.
Similar to, but not the same as, Array.push throwing TypeError for array.push is not a function
In brief:
const fn = (n) => {
let factors = [];
let index = 1;
while (n % 2 == 0){
let out = 2 ** index;
factors.push(out);
index++;
n /= 2;
}
}
This returns:
Uncaught TypeError: factors.push is not a function
(I have left out a lot of code that does not affect the issue.)
Edit update: WIP. Apparently, the loop this is enclosed in has an effect, as do other variable declarations.
With any luck, I will return with a different question, having solved the initial problem.
Nested loops seems to have been the actual problem, which means others could not reproduce.
const fn = (m, n) => {
let factors = [];
let index = 1;
for (let i = m; i <= n; i++) {
while (i % 2 == 0){
let out = 2 ** index;
factors.push(out);
index++;
n /= 2;
}
}}
For unknown reasons, this causes a type mismatch. The declaration of the array appears to be the cause.
This problem has been abandoned as the initiating function was completed by other methods.
Here! its working well, what might went wrong on your side?
const fn = (n) => {
let index = 1;
let factors = [];
while (n % 2 == 0){
let out = 2 ** index;
factors.push(out);
index++;
n /= 2;
}
return factors
}
document.write(fn(400));
I keep getting an issue with an infinite loop in both the FOR and WHILE loop. I am trying to nest a while loop that will stop running when the number given by allNum[i] reaches 1. I get an error that both my for and while loops have an infinite loop issue. I'm still learning how to use loops, I am not sure what I'm doing wrong.
let numbers = []
//create a loop to iterate through the numbers array
for (let i = 0, n = allNum.length; i < n; i++) {
//create a new variable to store sub arrays
let subArr = [];
//use a while to stop when the number is divided down to 1 and then store divisors in an array if (allNum[i] % n == 0) if true allNum[i]/n and subArr.push(n); if false n++
while (allNum[i] > 0) {
let c = 2;
//if true then divide the number by n and add the n (divisor) to subArr, in this case we have to try the same number again to divide by the new value of i so don't increase n
if (allNum[i] % c == 0) {
allNum[i] = allNum[i] / c;
subArr.push(c);
//if false then make n go up by 1 number
} else {
c++;
}
} //WHILE ENDS
numbers.push(subArr);
console.log(allNum[i]) //using for testing only
} //FOR ENDS
console.log(numbers, '<- divisors & array ->', allNum); //using for testing only
return numbers;
}
Just was performing simple task in JS which was to take integer as an input, divide it into single digits and multiply them ignoring all zeros in it.
I have solved it but had some troubles which were simply solved by changing the loop. I am just curious why the code did not work properly with the for loop and started to work as I it for for of loop. I could not find out the answer by my self. If somebody could tell where I am wrong.
First one works as intended, second one always returns 1.
function digitsMultip1(data) {
var stringg = data.toString().split("", data.lenght);
for (let elements of stringg) {
if (elements != 0) {
sum = parseInt(elements) * sum
} else {
continue
};
}
return sum;
}
console.log(digitsMultip1(12035))
function digitsMultip2(data) {
var sum = 1;
var stringg = data.toString().split("", data.lenght);
for (var i = 0; i > stringg.lenght; i++) {
if (stringg[i] != 0) {
sum = parseInt(stringg[i]) * sum
} else {
continue
};
}
return sum;
}
console.log(digitsMultip2(12035))
There is no big difference. for..of works in newer browsers
The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
Several typos
length spelled wrong
> (greater than) should be < (less than) in your for loop
Now they both work
function digitsMultip1(data) {
var sum=1, stringg = data.toString().split("");
for (let elements of stringg) {
if (elements != 0) {
sum *= parseInt(elements)
} else {
continue
};
}
return sum;
}
console.log(digitsMultip1(12035))
function digitsMultip2(data) {
var sum = 1, stringg = data.toString().split("");
for (var i = 0; i < stringg.length; i++) {
if (stringg[i] != 0) {
sum *= parseInt(stringg[i])
} else {
continue
};
}
return sum;
}
console.log(digitsMultip2(12035))
You might want to look at reduce
const reducer = (accumulator, currentValue) => {
currentValue = +currentValue || 1; return accumulator *= currentValue
}
console.log(String(12035).split("").reduce(reducer,1));
How can I change the function passed params?
function minus_num(num) {
num -= 1
}
var num_test = 10
while (num > 0){
minus_num(num_test)
}
console.log(num) // there I want to get the 0, but it is infinite loop, because the `num` will have a copy in the function.
How can I change the num_test itself?
You need the function to return the value after being subtracted, and then you need to assign the result of that to num_test.
But num is never explicitly declared in your code. You probably wanted to put num_test in the loop instead:
function minus_num(num) {
return num - 1
}
var num_test = 10
while (num_test > 0){
num_test = minus_num(num_test)
}
console.log(num_test)
Primitives are passed by value, so you cannot change them in place. Instead you must return the changed value from the function and assign it back to the same variable:
function minus_num(num) {
num -= 1;
return num;
}
var num_test = 10
while (num_test > 0) {
num_test = minus_num(num_test)
}
console.log(num_test);
For your current implementation, you will get an error that num is not defined because you never declared it before the usage.
Please read this post to find out more on variable passing to functions.
I think it should be
function minus_num(num) {
return num - 1
}
var num_test = 10
while (num_test > 0){
num_test = minus_num(num_test)
}
console.log(num_test)
I'm doing the factorialize algorithm challenge on FCC and I would really appreciate if someone with a greater knowledge than me would explain me what's wrong in the thinking process of my code
Im following these steps to factorialize a number:
Create a function with a parameter (num).
I create an if statement to accomplish the next task: factorialize(0) should return 1. If (num === 0) {return 1;}
Create an array inside the function.
Create a loop to iterate through num-1 numbers and push them into the array. So we add the current number + all the previous values to the array. Example: If our number is 5 we add 5, 4, 3, 2, 1.
Use the reduce method into the array to multiply the values of each number in the array (factorialize).
Return the given value.
My code:
function factorialize(num) {
if (num === 0) { return 1; }
else {var array = [];
for(i = num; i >= 1; i--){
var newArray = array.push[i];
newArray.reduce(function(previousVal, currentVal){
return previousVal * currentVal;
});
}
}
}
factorialize(5);
I am mainly getting 2 douts now. This way to solve the algorithm might not be the most efficient one okay but:
Is this a viable way to solve it?
Why am I getting "cannot read property 'reduce' of undefined".
Link to the challenge:
https://www.freecodecamp.org/challenges/factorialize-a-number
You can simply try this:
function factorialize(num) {
if (num === 0) { return 1; }
else {
for (var i = num - 1; i >= 1; i--) {
num *= i;
}
return num;
}
}
factorialize(5);