How to get loop value outside the loop - javascript

How to get the loop values outside the loop below example only prints the last value, For example if i wanted to print the loop results.
var result;
for (var i=0; i < 10; i++) {
result = i;
}
console.log(result);
Now how can i get the iterated values of the loop which are (1 to 10) in the console, because now i will only print the last value which is 10.

Put the log statement inside the loop where you set the value.
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result);
}
If you only want one output statement, you can concatenate your results before logging:
var result = "";
for (var i=0; i < 10; i++) {
result += i + " ";
}
console.log(result);
This will output 0 1 2 3 4 5 6 7 8 9 10

If you really want to log outside of the loop, wich is quite unnecessary in my opinion, may use an array? :
var result=[];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(...result);
http://jsbin.com/gogeluhavi/edit?console
If you want result make to log magically, you may uses setters and a Proxy, so called Observables.
Enter result=10 into this console, ive implemented a Observable for you: http://jsbin.com/xacujabuwo/edit?console ; You could also paste your for loop...

The Above answears are correct but I would like to clear it up for you so you understand it too.
In your original code you have declared the variable "result" outside the loop, then at each iteration a value is assigned to your variable. So that first time around "result" = 0 , second loop and the "result" = 1 and so on.
When the the for loop is finished it reads the next line which is your console.log() statment with the variable "result". The last time the variable "result" was modified was inside the for loop at the 10th iteration and thats where you let it equal to the iterator,therefore the value of iterator is 11.
In order to display something at every iteration, the console.log() must be placed inside the loop. Check below example
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result); // prints at every iteration
}

Since you didnt add jQuery tag I used only javascript.
Add a input hidden tag
<input id="idOfInput" style="visibility:hidden" type="text">
Set the desired value to the input
for (var i=0; i < 10; i++) {
result = i;
document.getElementById('idOfInput').value = result;
document.getElementById('idOfInput').change(); //note change() is to trigger the event
}
Add change event listener and get the value set in loop
var input = document.getElementById('idOfInput');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value); //you get the value here
});
hope it helps

var result=[];
for (var i=0; i <= 10; i++) {
result.push(i);
}
console.log("Result =>", result);

Related

Infinite Loop for finding a power set for a string

I'm working on a problem where I need to find all the power set of a given string which are all the possible subsets. I feel like I'm close with my current code but I can't figure out why I'm getting stuck on an infinite loop for my second iteration. I ran it through the debugger but I still can't seem to figure it out even though I'm sure it's very simple. When i = 0 then it goes to the second loop where j = 0 && j < 1 so for example if help is my given str argument then I would expect it to add j + '' and push it into my allSubsets array. The problem is that the j iteration will keep looping and doing j++ and will never stop. I'm not sure why this is. One particular question even if I solve this infinite loop - do I need to update the allSubsets.length in the iteration to keep it updated with the pushed in strings?
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
debugger;
for (let j = 0; j < allSubsets.length; j++) {
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
}
}
return allSubsets;
};
var sortLetters = (word => {
//convert string to an array
//use the sort to sort by letter
//convert array back to string and return
return word.split('').sort().join('');
})
Everytime you push to allSubSets, the length increases, and thus, your loop never ends. A declarative loop runs on the range of the initial loop. See below for a fix based on your code:
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
allSubsets.forEach( (_char, j) => { // declarative loop here
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
})
}
return allSubsets;
};
var sortLetters = (word => {
return word.split('').sort().join('');
})
From MDN web docs:
The range of elements processed by forEach() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach() begins will not be visited by callback. If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (See this example, below.)
See the fourth paragraph under descriptions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

Javascript:Push items in a list and print them with delay

I want to push items in a list using a for loop and print every step with a delay. Instead I get in every iteration the complete list.I guess this is a scope problem but I cant figure a solution.
Here is my code:
function printNumber(num,i){
setTimeout(()=>console.log(num),500*i);
}
let numbers = [50];
for(let i=1; i<=10; i++){
printNumber(numbers,i);
numbers.push(i);
}
That's because Javascript passes arrays by reference*, which means that the callback, which runs long after the loop is concluded, will all point to the same, updated, value of the array.
You need to copy the array every time to use the intermediate state. You can call printNumber this way:
printNumber([...numbers], i);
So that it will make a new copy of the array and iterations won't mess with each other.
* see Brian Thompson's comment for further clarification
You hand over the array instead of the value.
printNumber(i, i);
// ^
function printNumber(num, i) {
setTimeout(() => console.log(num), 500 * i);
}
let numbers = [50];
for (let i = 1; i <= 10; i++) {
printNumber(i, i);
numbers.push(i);
}
If you like to show all collected numbers, you could take a copy of the array.
function printNumber([...num], i) {
setTimeout(() => console.log(...num), 500 * i);
}
let numbers = [50];
for (let i = 1; i <= 10; i++) {
numbers.push(i);
printNumber(numbers, i);
}
I think you might be looking for something like in the below snippet. The array includes all values every iteration because the loop runs to completion before the setTimeout starts printing things.
Since arrays are stored as references, num is being mutated by numbers.push(i).
Passing the function a new array each loop will solve this.
function printNumber(num,i){
setTimeout(()=>console.log(num),500*i);
}
let numbers = [50];
for(let i=1; i<=10; i++){
// Create new array when you pass it here
printNumber([...numbers],i);
numbers.push(i);
}
setTimeout is a timer. It will execute anything INSIDE with a delay. It doesn't pause the rest of the code. By the time console.log execute your array is complete. So it will print the completed array.
let numbers = [50];
for(let i=1; i<=10; i++){
setTimeout(()=>{
console.log(numbers, i)
numbers.push(i);
},500*i);
}

Index does not exist JavaScript?

integrityCheck = function () {
var check = ['098f6bcd', '4621d373', 'cade4e83', '2627b4f6'];
for (var i = 0; i <= check.length; i++) {
checkIntegrityOfData(
i,
check[i]
);
}
}
There is probably a very obvious error in my part of the code but im new at JavaScript so i cant really see it.
Array index starts from 0, meaning if an array has 5 elements, the length would be 5 but the max index would be 4.
With your condition logic
You will need to fix your condition logic i <= check.length, last iteration of the loop will try to access check[4] but the last element in check will be in check[3].
Change your loop condition code to
for (var i = 0; i < check.length; i++) {
The problem is your loop goes up to and including the length of the array, however array length starts from 1 whereas array indexes start from 0. Change it to this:
for (var i = 0; i < check.length; i++) {
And it will work. (All I did was change the i<=check.length to i<check.length so it won't iterate over the last index, which is the thing making the error.

For loop adding undefined entry's

I'm using a couple of for loops to create an array. Problem is, on the second pass it adds 4 undefined variables and I can't see where they're coming from.
Note: the if statement is correct and only gets fired when they match.
The code :
for (var x = 0; x < galleryObject[1].length; x++) {
gallerys[x]= [];
for (var i = 0; i < galleryObject[2].length; i++) {
if (galleryObject[2][i].galId === galleryObject[1][x].id) {
gallerys[x][i] = {};
gallerys[x][i].filename=galleryObject[2][i].fileName
gallerys[x][i].caption =galleryObject[2][i].caption
}
}
}
Obviously the problem here in the fact that sometimes your IF statements returns false. In that case it tries to add an element to an array but some previous indexes are not specified, so it fills them with 'undefined'.
Try to change your code in the IF statement to:
if (galleryObject[2][i].galId === galleryObject[1][x].id) {
gallerys.push({
filename:galleryObject[2][i].fileName,
caption :galleryObject[2][i].caption
});
}

add values to one variable with for loop totalSum Javascript

I have some values that come randomized to an variable.
Now i want to add every value to each other to get an total sum but the loop wont add them together.
The index variable work when i console log it. but not the total sum of a current value and the index value.
Any tips ?
This is the loop
// The indexValue is values I get from an array//
var indexValue = index; // Random number from 1 - 10
var totalSum = 0;
for(var x = 0; x <indexValue; x++){
var currentValue = index[x];
totalSum += currentValue;
}
console.log(totalSum);
I'm assuming since you're referencing index[x] that index is an array. If so, you are assigning the wrong value to indexValue. Try this:
var indexValue = index.length;
What this does is assign the length of the array to the variable indexValue. Now the for loop will run from 0 to n where n is the length of the array.
This should get you the values you need.
Hope this helps.
EDIT:
Below is a link to a jsFiddle I created with your example and the code explained:
jsFiddle
var index = [1,2,3,4,5];
var indexValue = index.length; // It's imperative that this is an array
var totalSum = 0;
for(var x = 0; x <indexValue; x++){
totalSum += index[x];
}
alert(totalSum);
The code above is a modified version of what you posted. The current value is not needed and has been removed. In this case, I created an array and stored the values in index. The length is computed, and the values are added together.
For the easy sake of testing, I changed console.log(totalSum); to alert(totalSum);. It will produce the same value just the same.
Just a reference note on console.log. Some browsers (mainly IE) who do not attach the debugger to the process automatically without a page refresh will through an error as console will be undefined. Here is a quick fix for that:
if(window.console && window.console.log) {
console.log(totalSum);
}
This checks that (a) the console object is attached to the global window object and (b) that the log object of console is attached to the console object.
you probably want something like this:
var sum = 0;
for (var i=0; i < index.length; i++) {
sum += index[i];
}
console.log(sum);

Categories