Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
EDIT: Looks like I messed up by my method of posting. For future help to others who experience this problem, I will be cleaning up this question.
I've been learning about JavaScript recently and ran into an issue - I believe it's a bug, but I can't find anything about it or how to fix it. For some reason, I get stuck in an infinite for-loop, where I see a constant barrage of '0' instead of the expected '0 1 2'. This is my current setup:
for (var i = 0; i < 2; i = i++) {
console.log(i)
}
Any help would be much appreciated. For convenience, I took a video of it (20 seconds or so). [I realize that videos do not help those who are trying to help after doing some reading, but I think it could still help those who have the same issue as I did. Therefore I decided to keep the video link just for that reason.]
As extra info, I ran this through Windows 10 WSL (bash for windows), Ubuntu 16.04. I am using Visual Studio Code.
https://photos.app.goo.gl/aJEgY3hEJVTMwRmK6
Thanks ahead of time!
This behavior is expected:
Increment (++)
The increment operator increments (adds one to) its operand and returns a value.
If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.
If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.
The key being for i++ it returns the value before incrementing
The other key being that primitives in JS are immutable, so when you assign a number, a new number is created and held in that variable.
Therefore your loop is saying i = 0, then set i = 0, then the previous 0 is set to 1.
The usual way of doing this kind of loop is to just increment the value without reassignment:
for (var i = 0; i < 2; i++) {
console.log(i)
}
Remove the i =
Also, you may want to declare the variable i outside of the for, like this:
var i;
for (i = 0; i < 2; i++) {
console.log(i)
}
The reason I prefer to have the var in the for is that it is not creating a variable limited in scope to the for loop, it will still be at the same level.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm solving a challenge which has a sequence of integers from 1 to N, and the task is to find the missing integer in the sequence, and the one integer that is duplicated.
The constraints -
You are not allowed to sort the array.
Your solution should not time out for large values of N.
Ideally, your solution should not use extra space except the one provided by the input array (which can be modified).
My current code times out, I'm assuming that's because the complexity for finding the duplicate element might be O(N^2).
For the missing element, my algorithm is -
Create a variable, set it to 1, and loop until condition is true
In loop, check if variable is present in array, if so, increment variable and continue loop
If variable was not found in array, this was the missing element. Break out of loop.
This should run in O(N) time, so this part should be fine.
For the duplicate element, my approach was to check the first index and last index of every element in array. For unique elements, the index values would be the same, but it would be different for the duplicates.
This is where the problem lies, I think.
My code -
function solution(array) {
var missing = 0,
duplicate = 0;
let notFound = true;
let curr = 1;
while (notFound) {
if (array.indexOf(curr) === -1) {
notFound = false;
break;
}
curr++;
}
missing = curr;
duplicate = array.find((e, i, arr) => arr.indexOf(e) !== arr.lastIndexOf(e));
return [missing, duplicate];
}
console.log(solution([2, 3, 1, 4, 4, 6]));
I checked some related questions, like this and this, but couldn't get anything out of them.
How do I fix this?
I think you can hash your input array.
What I mean by that is, suppose your array is [4,1,5,6,3,1]
Here is a simple pseudo-code.
You can get duplicate element like this:
for i:array.length
array[array[i]] = array[i]*-1 // you found and marked first element of your array
if(array[i] > 0) //it would be positive if you found and marked an element twice.
array[array[i]] is the duplicate element
This runs in O(n)
Now to get the missing element, you can traverse the array again
for i:array.length
if (array[i] > 0 && array[i]!=duplicate element) //there would be two positive numbers, missing number and the duplicate
i = missing element
This O(n) again, so its O(n) overall.
If anything is unclear, you can ask. Sorry about preferring to write a pseudo-code instead of an explanation.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this code to add elements to my table and that part works perfectly fine. However, I want to add up the values of the last column in order to later print that on another part of the page. parseInt doesn't work for some reason (the values don't come back as integers and stay as strings, is there anything I have done wrong? Again, adding to the table works perfectly fine.
var hourC = 0;
var hourC =+ parseInt($(".hourCount").text(), 10);
alert(hourC);
Edit:
When I print the values of the variable hourC they don't add up to the previous value, they just stay next to each other. Example: 1 + 1 = 11 rather than 2. I don't see where my issue is and the answer for debugging didn't help since I still got the same result.
Final Edit:
I achieved what I wanted now through a different medium, I created an array and pushed the values into the array and then I used "join" to solve the issue.
If interested in what I was asking for here is a fiddle with the final result. (You can just change the console.log to alert)
Basic debugging skills.
parseInt works -- its a well tested function. If it broke in a browser, a lot of people would notice.
However, you haven't given any way to figure out what is going on with your code, since the real problem MUST be here:
$(".hourCount").text()
That must not contain whatever value you think it does.
Split your code up and use the debugger, or even console log, to see what the values are.
var hourC = 0;
var strValue = $(".hourCount").text();
alert(["strValue = ", strValue]);
hourC = parseInt(strValue, 10);
alert(hourC);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So, I started this project for school; I'm a beginner in javascript as you can see from the code, and I'm kinda stuck. First of all, I want to make a quiz where you have to introduce the amount of questions you want to answer, then answer them ofc. For the beginning I chose 7 questions with random answers to test it. The problem is that when I introduce 3 or less questions to answer it works fine, but when i go for more (+3 <=7) I get a strange error: index.html?fname=3:103 Uncaught TypeError: Cannot read property 'checked' of undefined(…). Here is my code:
My code
Im sorry for distrubing you with my stupidity! Have a nice day!
PS: I forgot to mention that this code isnt finished (I still need to style it), so dont judge me.
On line 68 of your code, you set y to be the number of questions the user asked for.
y=document.getElementById("myForm").elements[0].value;
This loop (starting on line 102) is where the error is coming from:
for(var i=0; i<y; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
Here's what happens: If you ask for 4 questions, this loop will keep running as long as i is less than 4. When i is 3, the if statement will be trying to access choices[3].checked. Remember, choices[3] is actually the 4th item in the array since indexes start at 0. Each question only has 3 choices, so when you ask for the 4th one you get undefined.
But you want this loop to look at 3 and only 3 answers for each question, regardless of how many questions there are in total. What you probably meant to write was this:
for(var i=0; i<3; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In javascript my understanding of the assignment operator is that it is the = sign.
var x = 120
but if you then wanted to do a for loop using this variable, you would normally shorten it for example:
for (x = 120; x < 140; x++);
so in between the paranthesis,it appears that the < symbol is also an assignment operator, as it states it is less than 140 and should be increased to 140.
Could someone explain more clarity on this or point me in the right direction, as most things i find shows this rightfully as the less than operator.
Your function myfunction (i=1; i < thisVar; i++) is a syntax error. We can't explain how that code works because it doesn't.
You may be thinking of the for loop:
for (i=1; i < thisVar; i++) {
}
The for loop has three expressions within its () that are separated with ;:
An initialization (i=1 in your case) that occurs at the very beginning, before the first test (see #2)
A test (i < thisVar in your case) that is performed prior to each iteration of the loop and determines whether the loop ends
An update (i++ in your case) that occurs after each loop iteration, before the test
This is intrinsic to how for loops work, and is not general-purpose; you can't just do that within () anywhere you like, it has to be on a for loop.
The < in that, as you can see above, is part of the test — a condition that must be true for the loop to continue. It's not an assignment. It's a relational operator comparing i with thisVar to determine whether i is less than thisVar.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I recently came across this little problem to solve on a website, counting the number of vowels in a string. I succeeded using a switch statement, but when I looked at the authors solution they had used the following function.
function vowel_count(str1) {
var vowel_list = 'aeiouAEIOU';
var vcount = 0;
for (var x = 0; x < str1.length ; x++) {
if (vowel_list.indexOf(str1[x]) !== -1) {
vcount += 1;
}
}
return vcount;
}
alert(vowel_count("The quick brown fox"));
Can anyone please explain what exactly is happening in the if statement,
I can see the index of whatever string that is passed to the function is being used but why would the statement == or !== -1. I'm a bit confused as to how the function is checking the string.
Thanks in advance.
The indexOf() function returns the index of an element we're looking for in a given array. However, if the element is nowhere to be found in the array, indexOf() returns -1 instead.
So in your case:
if (vowel_list.indexOf(str1[x]) !== -1) {
means something like "if the current letter can be found in my list of vowels".
Does that make sense ?
The indexOf method returns the position of the first occurrence of a specified value in a string. It returns -1 if the value to search for never occurs.
JavaScript, like most programming languages, starts counting from 0.
"foo".indexOf('f'); is 0.
The function returns -1 if the value isn't found.