Difference between two loops - javascript

The code below is the correct, working solution to an exercise I had to work out. I am wondering why my solution did not work.
The only difference I had was this line:
for (var i = contacts.length; i > 0; i--) {
Why it did not do the same just reversed direction?
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == name){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
} else{
return "No such property";
}
}
}
return "No such contact";

There are multiple problems in your code.
the first problem is that you start i = contacts.length and as you know there is no element in the array at the array length position
because arrays go from 0 to array.length-1.
the solution for that problem is var i = contacts.length - 1.
the second problem is that i never goes to zero because your stop condition is i > 0
then you never reach the first element of the array.
the solution is changing the stop condition to i >= 0

The two loops have different ranges.
If contacts.length had equalled 4, then i would have taken on these values:
console.log('ascending loop');
for (var i = 0; i < 4; i++) {console.log(i);}
console.log('descending loop');
for (var i = 4; i > 0; i--) {console.log(i);}

Array Start with 0.
Length Start with 1.
let say i want the last element from contact array
let contact = ['mo','so','do'];
console.log(contact[length])
It won't show a console. Y ? Because To get a last array.
You always need to -1 from the array.length

On the answer, the for counter go like 0 ... n, and on your for loop, the counter goes like n ... 1.
So, on your code, the index never is 0

Related

Print Prime Numbers (2,3,5,7)

I found the code for solving this problem, but I cannot figure out the logic of the solution.
let n = 10;
nextPrime:
for (let i = 2; i <= n; i++) {
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
alert( i );
}
I can't understand how the second for works, if it has an increment like the first, then the result should have been all numbers from 2 to 10, since the beginning of both for is the same number (2) ..
Can you please explain each iteration, for example why 4 is not displayed?
It’s using label to break the inner loop when it finds number is not prime . Outer loop is iterating the number and inner loop checks if it’s divisible between 2 to number.
Label break
the continue nextPrime used for just continue in the loop to the next iteration without finish all the code inside the loop.
like:
data:
for (let i = 1; i <= 3; i++) {
if(i === 2)
continue data;
console.log(i)
}
here when I get to I equal to 2 the code continue to the next number without continue to the rest of the code

Why won't my function work when I use splice?

I am trying to write a function which should calculate all prime numbers up to an input parameter and return it. I am doing this for practice.
I wrote this function in a few ways but I was trying to find new ways to do this for more practice and better performance. The last thing I tried was the code below:
function primes(num){
let s = []; // sieve
for(let i = 2; i <= num; i++){
s.push(i);
}
for(let i = 0; i < s.length; i++) {
for(let j = s[i]*s[i]; j <= num;) {
//console.log(j);
if(s.indexOf(j)!= -1){
s.splice(s.indexOf(j), 1, 0);
}
j+=s[i];
}
}
s = s.filter(a => a != 0);
return s;
}
console.log(primes(10));
The problem is that when I run this in a browser it keeps calculating and won't stop and I don't know why.
Note: when I comment out the splice and uncomment console.log(j); everything works as expected and logs are the things they should be but with splice, the browser keep calculating and won't stop.
I am using the latest version of Chrome but I don't think that can have anything to do with the problem.
Your problem lies in this line:
s.splice(s.indexOf(j), 1, 0);
Splice function third argument contains elements to be added in place of the removed elements. Which means that instead of removing elements, you are swapping their values with 0's, which then freezes your j-loop.
To fix it, simply omit third parameter.
function primes(num){
let s = []; // sieve
for(let i = 2; i <= num; i++){
s.push(i);
}
for(let i = 0; i < s.length; i++) {
for(let j = s[i]*s[i]; j <= num;) {
//console.log(j);
if(s.indexOf(j)!= -1){
s.splice(s.indexOf(j), 1);
}
j+=s[i];
}
}
return s;
}
console.log(primes(10));
Your problem is in this loop:
for(let j = s[i]*s[i]; j <= num;)
This for loop is looping forever because j is always less than or equal to num in whatever case you're testing. It is very difficult to determine exactly when this code will start looping infinitely because you are modifying the list as you loop.
In effect though, the splice command will be called setting some portion of the indexes in s to 0 which means that j+=s[i] will no longer get you out of the loop.

Forloop count isn't defined in JS?

Tried doing this for a class assignment but for whatever reason it is saying the count is not defined. Any suggestions?
var num = [1,2,3,4,5,6,7,8,9,10]
for(var num = 0; count < 11; num++) {
if(num % 3 ===0);
console.log(num);
}
I think you mean to use the num variable instead of count.
for(var num = 0; num < 11; num++) {
You are defining the 'num' variable. Setting it to 0 and then running the 'for' loop, adding 1 to 'num' for each loop until 'num' is no longer < 11.
try this...
var num = [1,2,3,4,5,6,7,8,9,10];
for (var count = 0; count < num.length; count++) {
if (num[count] % 3 == 0)
alert(num[count]);
}
Typically, Javascript for loops will have this format:
for (i = 0; i < 11; i++) {
//i = 0 > starting index
//i < 11 > ending index
//i++ > index increment
}
The reason why you ran into your error is because count is never defined as a variable, whereas the variable 'i' in my example was defined when I set the value of i=0.
Instead of thinking that you are looping through the integers within the num array, think of it like you're looping through the indexes of num. So within every loop, the i variable will represent which index of the array you're currently focusing on.
Helpful tips:
make sure you utilize num.length to get the ending index of your for loop
Use indexes to reference integers in an array: num[0] == 1,
num[1] == 2, num[2] == 3 ...

Why does my code always end with undefined?

I wrote this JavaScript code, but it always ends **undefined**mycode? What have I done wrong/ how can I prevent this in the future. I am running my code through the chrome javascript console.
Here is my code
//Reverse a string
//-------------------------//
//Input a string
var string = prompt("Please enter string");
//console.log(string);
//Find length of string
var stringLength = string.length;
//console.log(stringLength);
//Creating an empty string for outputting answer
var reversedString = "";
//Start from length of the string and work backwards, inputting letter 1 at a time.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
//Outputting the reversed string;
alert(reversedString);
Thanks for any answers in advance
Change your loop from
for (var i = stringLength; i >= 0; i--){
to
for (var i = stringLength-1; i >= 0; i--){
The problem is, the array indices in javascript are 0 based.
Lets say the string entered in the prompt is "abc", the length of the string is 3. In the loop, you access it as string[3] which is undefined. Hence the error.
Here is the fiddle demonstrating the updated code:
http://jsfiddle.net/rf1vmyzg/
adding string[i] is the last thing this code does before alerting you, so therefore the last string[i], (first element in your array, I assume) has the value of undefined.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
I do not know on the top of my head why this is, but I know that it is always a good idea to stick to conventions, and the one for for loops is:
for(var i = 0; i < [length variable];i++) {
...
}
Right code
for (var i = stringLength-1; i >= 0; i--){
reversedString += string[i];
console.log(string[i]);
}
You should not do string[i] instead do string.charAt(i); Also change stringLength to stringLength - 1. That should fix your problem. If you want this to work across different browsers use charAt notation. Javascript arrays start at 0 not 1 that is why you do length - 1 to get the last element. For example:
for a 10 element array indexes are 0-9. 10 is outside the boundaries of the array.
for (var i = (stringLength - 1); i >= 0; i--){
reversedString += string.charAt(i);
This is the correct answer.

Comparing array to var during iteration(cont.)

So here's my problem.. Might just be tired but, I want counter to ++ only if number has not occurred in array.
Meaning during the 4 iterations, counter should ++ only on iteration 1,3,4
var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
array.push(i);
number = temp[i];
}
document.write(counter);
But I'm drawing a blank here... Help?
(No this isn't homework)
if (array.indexOf(number) < 0)
counter++;
unfortunately JS doesn't have an "in_array", but it's pretty straight forward:
#MikeSamuel pointed out you can use indexOf (thanks Mike). So with that being said:
var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
array.push(i);
number = temp[i];
if (temp.indexOf(i)==-1) // much simpler, assuming you're checking if i is in temp.
counter++; // increase counter if it is not.
}
document.write(counter);
I'm not sure where you want the logic, so you'll have to figure that out or be more specific. Just know that you need to iterate through the array you're checking and check if the "needle" is in the "haystack" array.
EDIT Had the opposite, just added bool to check for existence.

Categories