I don't understand why this piece of code doesn't work:
let i = 0;
let arr = [];
while(i < 8){
arr[i] = i;
i++;
}
for(i = 0; arr[i]; i++) {
console.log("Result:", arr[i]);
}
I want to log each element of the array while the condition is true
I know that i equals to 8 after the while loop, but even an "i=0" before the for doesn't solve the issue (BTW why the i = 0 inside the for initialisation doesn't set it to 0?)
Can someone explain me what breaks the code?
for loops run until the condition is not true.
The first time around the loop i is 0 so arr[i] is arr[0] which you've populated with a 0.
0 is a false value, so the condition is false and the loop ends before the first iteration.
You probably want the condition to be i < arr.length.
In your first look you set arr[i] = i. In the second loop your condition is arr[i], and on the first iteration i = 0, which means arr[i] is 0 which evaluates to false causing your loop to exit.
Related
i am trying to figure out how this code works.
function Kth_greatest_in_array(arr, k) {
for (let i = 0; i < k; i++) {
let max_index = i;
const tmp = arr[i];
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[max_index]) {
max_index = j;
}
}
arr[i] = arr[max_index];
arr[max_index] = tmp;
}
return arr[k - 1];
}
console.log(Kth_greatest_in_array([1,2,6,4,5], 3))
As you can see the goal is to find third biggest value. But i don know how the second loop works. Could you explain it to me step by step. For example, what is the meaning of veriable j, especially why they typed let j = i +
This method basically performs an in-place sort of the arr array (but only "k" times - not a full sort), then returns the element (from the now partially sorted array) at index k-1.
The inner for loop looks through the remaining (unsorted) portion of the array to find the index of the item with the highest value:
if (arr[j] > arr[max_index]) {
max_index = j;
}
The specific statement you were asking about, let j = i + 1, means "declare a new variable, j, and set its initial value to one greater than the current iteration of the outer for loop". "j" is arbitrary and could be any valid identifier, it's just often used by convention when you have nested for loops since the outermost loop usually uses i (which is presumably short for "index").
At the end of each iteration of the outer for loop, these lines swap array elements so that this element is in the correct position:
arr[i] = arr[max_index];
arr[max_index] = tmp;
If you're curious to really understand the inner workings of a method like this, I'd highly encourage you to step through it with a debugger - it can be a great learning experience. Even just the tried-and-true method of sprinkling some temporary console.log statements can help illuminate what's going on (e.g., print the state of arr and max_index after every outer and inner loop iteration).
function insertionSort(arr) {
var length = arr.length,
val,
i,
j;
for(i = 0; i < length; i++) {
value = arr[i];
for(j = i - 1; j > -1 && arr[j] > value; j--) {
arr[j+1] = arr[j]
}
arr[j+1] = value;
}
return arr;
}
console.log(insertionSort([6,1,23,4,2,3]))
I am looking at an example of the insertion sort algorithm encoded in javascript, and having trouble understanding why it passes the conditional of the inner for loop. To be clear, this algorithm is correct -- I'm just having difficulty understanding why.
If j is initialized with i - 1, then the value of j is -1, since i is initialized at 0. In the first part of the conditional it states j > -1, which means it won't pass the this test, since j is not greater than -1.
Can someone tell me what I am missing?
You're right, the first iteration will not enter the second loop, but this is okay. Notice what that loop is doing. It's swapping array[j+1] with array[j]. When i == 0, then j == -1. You can't swap array[0] with array[-1], since it doesn't exist. This is a clever way of bypassing that issue.
However, this only happens on the first iteration. Subsequent iterations will enter the loop as expected.
Recently I stole some javascript to select an option in a select element:
var el=document.getElementById('mySelect');
var opts=el.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == 'Apple') {
el.selectedIndex = j;
break;
}
}
It works fine, but as I looked at it I realized it was different from what I would have written:
var el=document.getElementById('mySelect');
for (var j = 0; j < el.options.length; j++) {
if (el.options[j].value == 'Apple') {
el.selectedIndex = j;
break;
}
}
In looking at the first code, what stops the loop if 'Apple' is not found? Which one is 'better'?
In either case, the second expression determines if the loop should continue or stop. In yours,
for (var j = 0; j < el.options.length; j++) {}
it's straightforward, j will increment and as long as j is less than the options length it's true, and at some point it is equal to the length and then it stops. In the other one,
for (var opt, j = 0; opt = opts[j]; j++) {}
the difference is that they are declaring a variable opt and in the second expression set it to the (also incrementing) array index. At some point, j goes beyond the bounds of the array, and opts[j] is undefined. And since an equality expression in JS is the value of the right site, that expression is also undefined, which is falsy, and the loop stops.
As for which is better? Both work. But as you had to scratch your head and wonder about one of them, how much do you want to depend on code that's more difficult to read?
Long story short:
In your for loop var opt is executed once after which you have subsequent opt = data[i].
This is important because:
var opt, data = [1, 2]; // defined once
console.log(opt = data[0]) // 1
console.log(opt = data[1]) // 2
console.log(opt = data[2]) // undefined
When the for loop condition evaluates to falsy it will halt.
So in your case it does stop when opt = data[i] ends up being a falsy value - undefined
Which is at the point of i being 5 and data[i] becoming undefined and being assigned to opt ... which returns as a final result undefined.
You should also consider using this (if ES6 is an option):
var el=document.getElementById('mySelect');
el.selectedIndex = el.options.findIndex(x => x.value === 'Apple')
It is shorted and easier to read :).
Why, if a I nest a for-loop executed on an empty array in another for-loop executed on a not empty array, I get a browser-blocking infinite loop as result?
var links = [];
var anchors = ['a', 'b', 'c'];
// not empty loop
for(var i=0; i<anchors.length;i++) {
console.log(anchors[i]);
// empty loop
for(var i=0; i<links.length;i++) {
console.log(links[i]);
}
}
The code inside for(var i=0; i<links.length;i++) is not even evaluated, so why this behavior?
When the second loop executes, you are resetting the i variable (it's equal to 1 after the first cycle in the first for loop) to 0. The same situation in the first loop, when the second one has done first cycle (and the i has 1 value), it's being reseted to 0 once again by the first loop. And so on... till the world's end.
Hovewer - like Ori pointed - if you would use let to declare i variable inside the loops, everything would work smoothly.
var links = [];
var anchors = ['a', 'b', 'c'];
// not empty loop
for (let i = 0; i < anchors.length; i++) {
console.log(anchors[i]);
// empty loop
for (let i = 0; i < links.length; i++) {
console.log(links[i]);
}
}
Ok, so if the nested array is empy, its length is 0, so:
for(var i=0; i<0;i++) {
console.log(links[i]);
}
"i" will never be 0 and the loop will be infinite...
Because link array has length = 0. When you will execute this code
for(var i=0; i<links.length;i++)
1) variable assigned value 0
2) get links.length - it is 0.
3) because 0 < 1,
console.log(links[i]);
will not evaluated
I have written this bit of code that sums the values of array. Can some one please explain why I'm getting undefined in the last console.log statement.
var array = [2,3,4,5,6,7];
var sum = 0;
for(var i = 0; i < array.length; i++) {
sum = array[i] + sum;
}
console.log(sum);
console.log(array[i]);
That's because the loop performed i++ and now i is equal to array.length.
JavaScript returns the primitive value undefined when you're trying to access object properties that were not previously defined.
The array however is only filled between places 0 and array.length - 1 since JavaScript arrays are 0 based.