Is there an alternative to javascript loop? [closed] - javascript

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
I was working on a program, I came to a point where I wanted to loop a value and then use it to test user's input with the if statement, but the problem was that I couldn't use the value of the loop.
At least that's what I think, then I tried placing the if statement as one of the codes that the loop statement is supposed to execute, surprisingly it worked, but when I tried more that one if statement (ie. else if), it only executed one of my if statement.
Please is there an alternative method to use?
Below is the code (Input a Number between 0 and 10):
<input type="number" id="i" />
<input type="button" value="submit" onclick="result()" />
<p id="k"></p>
<script>
function result (){
//first method
var x= i.value;
var y = 0
while (y<10){
y++
}
if (x==y) {
document.getElementById("k").innerHTML = "correct"
}
/ * it didn't work probably because the if statement assumes y to be 0. /*
//second method
while (y<10){
y++
if (x==y) {
document.getElementById("k").innerHTML = "correct"
}
else if (x >y ) {
document.getElementById("k").innerHTML ="wrong"
}
}
//it only tested one of the if statement
</script>
Or is there another way instead of looping?

Some issues with your code:
The first instance the if statement is not inside the loop.
Once you're done with the loop you want to exit it with a break;
In the 2nd instance the else if block should appear after the loop. Why? For example the user enters 2. In the first iteration of the loop 2==1 will fail, 2 > 1 will be true, but it's not the wrong answer. x > y is only the wrong answer when y itself is >= 10.
Instead of looping you can check if the value itself is greater than 0 and less than 10, you can combine as many conditions as you want e.g.
function result (){
//first method
var x= Number(i.value); // Number isn't necessary.
if ( (x > 0) && (x < 10) ) { // The && means "and", so if x is greater than 0 and less than 10.
document.getElementById("k").innerHTML = "correct";
} else {
document.getElementById("k").innerHTML = "wrong";
}
}

Related

I need to sort out this algorithm [closed]

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 3 years ago.
Improve this question
could you please your help.
how to answer this question ?
I need your help thinks
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * n ;
}
}
factorial(6)
this is not right.. i need to use writing code with Loop javascript.
Get the factorial of n. The inheritance of n is the number 1 through n multiplied by all numbers.
example)
answer should be like this
factorial(4); // => 24
factorial(5); // => 120
One way is to use a simple for loop.
var answer = 1;
for(var i = 2; i <= n; i++)
{
answer *= i;
}
return answer;
You can also do this recursively by multiplying your input by the result of the previous value.
function factorial(n){
if(n <= 1) return 1;
return n * factorial(n-1);
}

Javascript for loop with if statement not reaching the else if statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
why wont this reach the else if and return (i + 0) / 2? Also, why wont the alert give me i + 0 for a 2 digit value? (ie: 10, 20, 30, 40, etc. Any help would be appreciated.
var key= "OSN0MSA9991UNAAM8ELDPBD9F57BD6PU6BVBN54CDLEGDSUSNS";
var x = 0;
if (key[20] != "P" || key[18] != "P") {
x = 0;
for (i=0;i<10;i++) {
if (key[26] == i) {
x = i + 0;
alert(x);
}
};
} else if (key[20] == "P") {
for (i=9;i>-1;i--) {
if (key[26] == i) {
x = (i + 0) / 2;
alert(x);
}
};
};
your value at key[18] is "L" so if condition is always true and you will get an alert with value 7
It's not hitting the "else if" I believe because your array starts at 0, and the key[20] is in fact a P, so it's going to always fall in to the first condition and not hit the else if. EDIT: My mistake, misread. You could alert out the key[20] and key[18] to see what it thinks those values are.
Your issue is with the key[18]. Since you have an OR and key[18] = L (hence not P)..

JavaScript factorial [closed]

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 8 years ago.
Improve this question
Cant wrap my head around arguments.callee and why truefactorial = 120. Some help would be much appreciated
function factorial(num){
if (num <= 1) {
return 1;
} else {
return num * arguments.callee(num-1)
}
}
var trueFactorial = factorial;
factorial = function(){
return 0;
};
alert(trueFactorial(5)); //120
Inside a function, arguments.callee refers to that function.
So factorial is recursive - it calls itself. No matter what name you might use for it.
Redefining the name factorial to reference a different function has no affect on the first definition, because nowhere in that first definition does it use the name factorial.
As noted in the comments arguments.callee is deprecated and you should not use it (it won't even work if your code is running in strict mode). However, if you replace arguments.callee with factorial in your example, the end result will not do anything useful:
function factorial(num){
if (num <= 1) {
return 1;
} else {
return num * factorial(num-1);
}
}
var trueFactorial = factorial;
factorial = function(){
return 0;
};
alert(trueFactorial(5)); // 0
This is because factorial gets reassigned before your function is called, and when it ultimately tries to call factorial() inside the function, the new factorial() just produces a 0.
There is a way around this, and that is to use a named function expression:
var factorial = function factorial (num) { // <--- This line
if (num <= 1) {
return 1;
} else {
return num * factorial(num-1);
}
}
var trueFactorial = factorial;
factorial = function(){
return 0;
};
alert(trueFactorial(5)); // 120 (Yay!)
If you do this, even if the factorial variable is reassigned outside of the function, it will keep its original meaning inside the function, and will not break.

Javascript Equal Probability [closed]

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 8 years ago.
Improve this question
Hi I need a probability in javascript that is a function and returns X 1 in every 2 times and Y 1 in every 30.2 times. The rest of the time the function should returns Z.
The function should be able to be called many times in a row.
This is what I have came up with so far
probability(){
var randomNumber = random() * 100;
if (randomNumber > 50) {
x()
}
else if (randomNumber > 3.31125827815 ) {
y()
}
else {
z()
}
}
Currently, your function will call y() if randomNumber is between 3.3 and 50. You probably want < instead of >
else if (randomNumber < 3.31125827815 ) {
It might make it a bit more readable to sort the intervals in ascending order:
function probability(){
var r = random();
if (r < 1/30.2){
y();
}else if(r < 0.5){
z();
}else{
x();
}
}

How to write an IF else statement without 'else' in JavaScript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I can't use else in my script; how can I implement an if else statement without using else?
I'm trying to resize a div:
function hideTable(){
var table = document.getElementById('PDemo');
if(table.style.width == "50%") table.style.width = "150px";
if(table.style.width == "150px") table.style.width = "50%";
}
This script doesn't work because as soon as the first if statement is executed, the condition for the second if statement becomes true, so that executes too, and thus nothing changes.
The ternary operator:
condition ? execTrue() : execFalse();
This is equivalent to:
if (condition) {
execTrue();
}
else {
execFalse();
}
You can write an if/else in 1 line, just don't press enter...
if (condition) { execTrue(); } else { execFalse(); }
Further, you can write any statement of arbitrary complexity on one line:
if(condition1) { exec1(); } else if(condition2) { exec2(); } else { execFalse() }
If you're having the issue where the second if statement executes as well, you want to impose mutual exclusion, i.e., using else if instead of just if on each subsequent conditional.
Save the value into a different variable.
function hideTable(){
var table = document.getElementById('PDemo');
var width = table.style.width;
if(width == "50%") table.style.width = "150px";
if(width == "150px") table.style.width = "50%";
}
If you can't use an else (and that is crazy), use a switch.
switch (table.style.width) {
case '50%':
...
break;
case '150px':
...
break;
}
if(/*condition a*/){/*statements a*/}else if(/*condition b*/){/*statements b*/}else{/*statements c/*}
One line only.
With a while loop for the sake of uniqueness.
while (!resized){
if(width == "50%") {table.style.width = "150px";resized=true;break};
if(width == "150px") table.style.width = "50%";resized=true;break};
resized=true;
}
The && operator is called a short-circuit operator. It will return the value of the second operand based on the value of the first operand.
For example: (explanation : If 'profile' permission exists in permArray then load the user's profile)
isPermitted(permArray, 'profile') && loadProfile();
The && operator is useful also for checking for null objects before accessing their attributes. For example...
var name = person && person.getName();

Categories

Resources