I have a series of radio buttons on my page that, when checked, establish certain conditions. For each condition, a value is subtracted from the PRICE, which is the final variable that is provided to the user.
if (condition1==0){price-=5;}
if (condition2==1){price-=4;}
if (condition3==1){price-=10;}
var minimum = 1;
if (price < minimum){price = minimum;)
The conditions are all working exactly as I want. For this code group, I basically don't want "price" to go below 1. My problem is that this is creating an error and I am really not sure why. I am more familiar with Java, so perhaps I am running into an error that Javascript throws that I am not familiar with.
What can I do to make sure that my "price" variable does not fall below my "minimum" variable, without throwing an error?
You have a parentheses ) after price = minimum; rather than a curly bracket } which is why your code is creating an error.
Here is the changes.
Before:
if (price < minimum){price = minimum;)
After:
if (price < minimum){price = minimum;}
^
You could do something like this:
if (condition1 === 0) { price = Math.max(price - 5, 1); }
Or generalize it into a function:
function reducePriceBy(amount) {
return Math.max(price - amount, 1);
}
And then
if (condition1 === 0) { price = reducePriceBy(5); }
You've got a syntax error to start: if (price < minimum){price = minimum;}
The last parentheses should have been a brace.
Related
I'm not a programmer by any means. I'm an animator trying to use JS expressions in After Effects. I'm getting an "Undefined value used in expression" error on line 1 where I define a variable.I already showed it to my friend on discord who is a cs major, and he had no clue what was wrong with it.
Here's just a paste of the code if you need it:
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1
if (count % 2 == 0){
thisProperty = 95
} else {
thisProperty = 20
};
} ;
Ok I don't know why the hell this fixed it, but I changed the name of the variable from "count" to just "x" and it works now. Go figure
Try it.
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1;
if (count % 2 == 0){
thisProperty = 95;
} else {
thisProperty = 20;
}
}
thisProperty;
In your code, thisProperty has become an ordinary variable. If you write its name at the end of the code, then its value will be assigned to the property.
In AE, if there is nothing inside an if statement or the if statement contains malformed/error code you will receive this error. Put a temp value inside the curly braces or something to process and ensure nothing inside will throw an error.
I also received this error with this:
pastTime = timeToFrames(time)-1;
curPos = transform.xPosition;
pastPos = transform.xPosition.valueAtTime(framesToTime(pastTime));
if (curPos-pastPos[0] != 0) {
// Here is the problem in my case. added a value here 99 to fix until finished testing.
}
else {
effect("Angle Control")("Angle")
}
if/else statements are strict
The syntax for if/else statements is strict in the JavaScript engine
and need to be written for standardized JavaScript.
https://helpx.adobe.com/after-effects/using/expression-language-reference.html*
I got this error because there was a missing semicolon.
I was reading the doc, and after tweaking its sample code, I managed to get compiler barked at me about cyclic dependencies like this:
<script>
let count = 0;
$: double = count * 2;
$: if (double >= 20) {
alert(`count is dangerously high!`);
count = 9;
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
I asked on discord how to fix it, and people suggested that I should hide the dependencies from the compiler like this:
<script>
let count = 0;
$: double = count * 2;
function resetCount() {
count = 9;
}
$: if (double >= 20) {
alert(`count is dangerously high!`);
resetCount();
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
It works, but I got a couple questions:
Battling with the compiler doesn't sound right to me, is there any other better ways to fix this?
A more general question is that does cyclic dependencies happen quite often to people who have written large amount of svelte code? Is it normal or it usually signals a bad design?
Thanks.
The answer from #morphyish sort-of provides a fix, because as they stated:
a reactive statement can't trigger itself
However, I see that as somewhat of a technicality, and still see the provided solution as conceptually having a cyclic dependency: we still have count -> double -> count -> ....
And because we've bypassed this cyclic dependency warning by merging the statements into a single reactive block, we've actually also introduced a bug:
This bug occurs because the double value is set to 10 * 2 = 20 at the beginning of the reactive block, then count is set to 9 within the if-statement, but then double is not set back to 9 * 2 = 18 because the reactive block doesn't trigger again.
My suggestion in this, and similar cases would be to re-evaluate what your dependencies actually are in order to remove these cycles:
double = count * 2;
^ So double depends on count, that one's easy.
if (double >= 20) {
alert('count is dangerously high!');
count = 9;
}
^ At first glance it might seem like our count-reset logic depends on double, but seeing as we've already established that double depends on count – and this block is ultimately concerned with count – this logic really depends on count not double.
So in my view, the best solution would be to modify the conditional to match the actual dependency:
<script>
let count = 0;
$: double = count * 2;
$: if (count >= 10) {
alert(`count is dangerously high!`);
count = 9;
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
You could fix this issue by organizing your code slightly differently:
<script>
let count = 0;
let double;
$: {
double = count * 2;
if (double >= 20) {
alert(`count is dangerously high!`);
count = 9;
}
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
You can group reactive statements together using {} with a small caveat: Svelte won't automatically write the variable declaration as it would otherwise.
I've never run into this issue before, but in your case it looks like both statement are dependent on count being updated, albeit indirectly for the second one. So it makes sense to actually group them into a single statement.
It also solves your issue as a reactive statement can't trigger itself.
However it means that if you want to also update double you would need to do it explicitly.
I've got some javascript to change the input value via plus/minus buttons.
I now need to save the value after the value has been decremented in a variable and output it as a number.
The javascript for the decrement looks something like this:
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
var test = parseInt($('input[id='+fieldName+']').val(currentVal - 1).val());
alert(test);
}
So as you can see I'm trying to get the updated value of the input in a variable called 'test', but all I'm getting is a NaN. Any ideas how to output the updated value of the input as a number within my test variable?
As #trincot said we cannot re-produce your situation. But the reason a NaN would be returned is because.
parseInt Returns an integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
let a = '1'
let b = 'Two'
console.log(parseInt(a));
// 1
console.log(parseInt(b));
// NaN
console.log(parseInt(undefined))
// NaN
You can use double Tilda operator ~~ which behaves like Math.floor() except will return you 0 if the value is not a number.
I believe this is the solution you are looking for:
let inputField = document.querySelector('input[name="fieldName"]');
increment = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
inputField.value = currentValue + 1;
};
decrement = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
if (currentValue > 0) {
inputField.value = currentValue - 1;
}
};
<input type="number" name="fieldName" value="0" />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
Hope this helps,
Something showed up to me.
You are using jquery (I think it's right cause of the $ selector), and you are getting the ID with bracket notation.
Why not using something like
var selector = '#' + fieldName;
Then
$(selector)???
Another thing, usually when I'm trying something with javascript, I try it into the developer tool's console of my browser.
Doing it step by step avoid mistakes
I know there are a number of ways to complete this challenge and I can simply a different approach to pass the requirement however I am struggling to understand what's wrong with my code.
Challenge - https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/counting-cards/
Any help would be much appreciated.
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count+=0;
} else (count--;)
if (count > 0){
return count + " Bet";
} else (
return count + " Hold";
)
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
Firstly, when you try to execute your code, you should be seeing a Syntax Error, pointing to the semicolon in (count--;). The reason for this is: else expects a statements, if it sees a parenthesis it means the statement is an expression, and in an expression, semicolons can't appear inside parentheses (this is rather simplified). The correct way to write it is either without parentheses (generally frowned upon) as else count--;, or with curly braces: else { count--; }.
When you fix that error, there will be another one of the same kind, as you seem to systematically use parentheses instead of curly braces after else.
After that, your code kind of works. There's questionable comparisons of card, that can be a letter or a number, with an integer, but it coincidentally works the way you hope it does (because 'K', 'Q' and 'J' happen to be evaluated as greater than 7 and 10.) It would be better to not rely on such magic, and have a translation table between letters and values - or at least, if you're going to rely on magic, comment so that readers are aware you are aware of the magic. Also, count+=0 is a void statement, it does nothing, and could have been left out. That leaves you with an empty else if, but that's not an error. However, it would probably be much more readable if you had if (card < 7) { count--; } else if (card >= 10) { count++; }.
stupid mistake's.
answer is below:
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count;
} else {count--;
}
if (count > 0){
return count + " Bet"
} else {
return count + " Hold"
}
// Only change code above this line
}
I'm totally not a Math whiz kid here, but have put together a function with the great help of StackOverflow (and a lot of trial and error) that generates a random serial number from a Formula, group of Letters/Numbers, and array (so as to not duplicate values).
So, my current formula is as follows:
$.extend({
generateSerial: function(formula, chrs, checks) {
var formula = formula && formula != "" ? formula : 'XXX-XXX-XXX-XXX-XXX', // Default Formula to use, should change to what's most commonly used!
chrs = chrs && chrs != "" ? chrs : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", // Default characters to randomize, if not defined!
len = (formula.match(/X/g) || []).length,
indices = [],
rand;
// Get all "-" char indexes
for(var i=0; i < formula.length; i++) {
if (formula[i] === "-") indices.push(i);
}
do {
rand = Array(len).join().split(',').map(function() {
return chrs.charAt(Math.floor(Math.random() * chrs.length));
}).join('');
// Rebuild string!
if (indices && indices.length > 0)
{
for(var x=0; x < indices.length; x++)
rand = rand.insert(indices[x], '-');
}
} while (checks && $.inArray(rand, checks) !== -1);
return rand;
}
});
Ok, so, what I need to be able to do is to find total possible values and make sure that it is possible to generate a unique serial number before actually doing so.
For example:
var num = $.generateSerial('XX', 'AB', new Array('AB', 'BA', 'AA', 'BB'));
This will cause the code to do an infinite loop, since there are no more possibilties here, other than the ones being excluded from the extension. So this will cause browser to crash. What I need to be able to do here is to be able to get the number of possible unique values here and if it is greater than 0, continue, otherwise, don't continue, maybe an alert for an error would be fine.
Also, keep in mind, could also do this in a loop so as to not repeat serials already generated:
var currSerials = [];
for (var x = 0; x < 5; x++)
{
var output = $.generateSerial('XXX-XXX-XXX', '0123456789', currSerials);
currSerials.push(output);
}
But the important thing here, is how to get total possible unique values from within the generateSerial function itself? We have the length, characters, and exclusions array also in here (checks). This would seem more like a math question, and I'm not expert in Math. Could use some help here.
Thanks guys :)
Here is a jsFiddle of it working nicely because there are more possible choices than 16: http://jsfiddle.net/qpw66bwb/1/
And here is a jsFiddle of the problem I am facing: Just click the "Generate Serials" button to see the problem (it continuously loops, never finishes), it wants to create 16 serials, but 16 possible choices are not even possible with 2 characters and only using A and B characters: http://jsfiddle.net/qpw66bwb/2/
I need to catch the loop here and exit out of it, if it is not able to generate a random number somehow. But how?
The number of possible serials is len * chrs.length, assuming all the characters in chrs are different. The serial contains len characters to fill in randomly, and chrs.length is the number of possible characters in each position of that.