Hello I'm new to programming so please don't mind my silly questions. And please help me!
So, I was learning loops and started with for loop. I wanted to display :
1
11
21
31
41
51
61
71
81
91
(10 getting added to 1)
So I was referring a youtube video and it suggested the following way :
<html>
<title>I'm Learning</title>
</html>
<body>
<script>
for (var a = 1; a<=100;a = a+10){
document.write(a + "<br>")
}
</script>
</body>
</html>
Which worked. But, when I removed a = from for (var a = 1; a<=100;a = a+10) I thought it should still work as the value of a will still get changed. But, the webpage kept loading and after a while my laptop hanged. This happened twice. The webpage did not even load! So can anyone please help me with this? Please explain me if possible that why this error occurred. Thank You.
I was expecting that the output would not change.
You can do it also By a += 10 you need to assign the new value with the = aka the assign operator and it should still work :) you can't just blindly a + 10 unless you are doing it with an increment of 1 then you can do something like a++
Related
I'm trying to 'gamify' my website to engage learners. I am still incredibly new to JavaScript so I apologize in advance. There are dozens of similar articles, but none that match my needs closely and I have tried and failed to implement a fix with other similar questions - sorry (I have tried hard!)
Across approximately 10 pages, inside the navbar, I want to insert a counter. The code below is using the ID 'score-counter' to do this, and I've tried using localStorage to retain the score of that learner across each page. I've managed to get it to work (somewhat) but instead of adding 10 to the original value, it's creating an entirely new counter and starting from scratch.
I want each button to only be clickable once (per page refresh) so I have tried to remove the eventListener after each button is clicked. I also want a straight-forward way to add more buttons to the counter system, so I've tried to keep it to the two simple classes 'increment-button' and 'first-click'.
<button class="first-click increment-button">Add 10 to the value!</button>
<div id="score-counter">0</div> <!-- DISPLAYS THE COUNT -->
let score = localStorage.getItem("score") || 0;
const incrementButtons = document.querySelectorAll(".increment-button");
const scoreCounter = document.getElementById("score-counter");
scoreCounter.textContent = score;
for (let button of incrementButtons) {
button.addEventListener("click", function(){
if(this.classList.contains("first-click")) {
score += 10;
localStorage.setItem("score", score);
this.classList.remove("first-click");
}
});
}
The output currently keeps doing this: 201010101010
It's saving the output successfully, but instead of adding a value of 10 to the original score, it's creating a whole new score and starting from 0 again. Does this make sense?
I've tried changing the JavaScript to count up from the value of 0
let score = localStorage.getItem("score") || 0;
I've also tried tweaking the score value
if(this.classList.contains("first-click")) {
score = scoreCounter + 10;
I've tried looking through various StackOverflow and other web resources for similar problems but have struggled to found any answer that fits what I'm trying to achieve. Can anyone offer any advice? Thanks in advance!
You need to convert the string you get from localStorage.getItem to a number. This can be done with the unary plus operator.
let score = +localStorage.getItem("score") || 0;
Okay first of all thank you for your time. This has been driving me crazy.
So after a lot of digging I'm now properly "talking" with a scale through RS232 which means talking to it using HEX.
So I've been able to send data to the scale and get it back as needed. What I'm getting when I process it on node.js though is making me crazy.
The raw data coming through after concatenation is
<Buffer 06 02 30 32 1b 33 1b 31 31 34 34 35 1b 30 30 30 31 32 30 1b 30 30 31 33 37 33 03>
Which I'm properly converting to string like this:
var coiso = Buffer.from(Buffer.concat(porquinho), 'ascii').toString('hex');
And getting as a result this:
060230321b331b31313434351b3030303132301b30303133373303
If I get this value onto any online HEX to ASCII website (for example this) the result I'm getting is the correct one which should be:
02311445000120001373
However if I use any javascript function in node for the conversion including the same that website uses:
function OnConvert(doom)
{
hex = doom;
hex = hex.match(/[0-9A-Fa-f]{2}/g);
len = hex.length;
if( len==0 ) return;
txt='';
for(i=0; i<len; i++)
{
h = hex[i];
code = parseInt(h,16);
t = String.fromCharCode(code);
txt += t;
}
return txt;
}
The result I get without exception is this:
0214450012001373
Which is completely different as I'm losing one digit of the weight in the scale as well as one digit from the calculated price!
What the f*ck am I doing wrong here?
Please Help me out... It's driving me nuts!
Thank you in advance,
Kind Regards:
João Moreira
UPDATE As pointed out in the comments by ChrisG, if you use the exact same function in the browser the result is correct (check it -> codepen)! Is this some node.js quirk???? I'm using node v8.9.3.
So after A LOT of testing and digging I noticed the results in node were different in the windows commandline (I was on a mac).
So after I tested for the length of the string instead of its content I found out that it was exactly the same everywhere which basically means this is a problem with the content of the string being perceived as something else by the command line... thank you very much Apple!
So if you work with SERIAL PORTS and communication protocols that envolve HEX or ASCII maybe it's best if you don't use the command line for it.
Just a small advice people!!!
I want to show up all numbers between -10 and 19 but my google chrome console returning me just one number in while loop. what is the solution of this problem?
any idea? how can i solve this problem?
console.log("i want to print all numbers between -10 to 19");
var counter=-10;
while(counter < 20) { console.log(counter); counter++; }
Change your filter level. You can use "Info" or "Verbose" but not "Warnings" and "Errors"
Our JavaScript application fails in very strange ways when running on iOS 10 beta 2 and beta 3 (running on iPhone 6). When looking at logs I can see that arrays contain NaN's and 0x00's in unexpected places. I managed to produce a test program that can quite reliably reproduce the behavior.
I have filled a bug report with Apple but haven't heard back so I am a bit concerned whether this will be fixed or not. So as a first thing, I would like to hear if someone can reproduce it and at least confirm there is a bug (and not just a misunderstanding on my part etc.). I'm fairly sure of this myself, but always good to be on the safe side! Could also be others have encountered it and found a workaround or maybe if some WebKit developers run into it, they might be able to help.
Test program showing bug
Here's the test progarm. The problem doesn't occur every time but the JavaScript code in the page can detect when it occurred and will keep refreshing the page until it occurs. On a non-affected browser, this means the page will keep refreshing. On an affected browser (such as Safari on iOS 10 beta 2 and beta 3 running on an iPhone 6) the refreshing will stop after some iterations (typically 5-10) and the display error.
The program operates by creating an uint8array of size 8192 (it seems smaller array sizes causes the error to be more rare). It will fill this array with dummy values, then call "toStr" which first allocates a new plain Array, then copies the contents of the uint8array to the plain array, narrowing each element along the way. While doing this it builds up a string containing the original value and the copied value. When the error occurs, the element in the target array turns out to be NaN which should not be able to occur since it by construction contains only integers. The doTest() function tests for whether such a NaN value is contained in the resulting string which shows that the error has occurred.
Note that within each refresh, the program runs 20 iterations and here it is also random which iteration that fails. However, I have observed that if the error doesn't occur among the first 20 of iterations, it is not likely to occur at all within this page load even if one ran an indefinite number of iterations, and this is the reason why I added the reload page logic.
Note that the program logic itself is completely deterministic so every run should be the same, which is also the case on other browsers. More detail can be seen by removing the comments from the log() statement in the doTest() function so it prints out the array.
Note that the problem seems to go away if the function "narrow" is inlined rather than being a separate function (even though these two programs should of course be semantically equivalent). Also, if one omits the shift from "state >> 8" the error also seemingly goes away so either the exact array values are significant or this rewrite somehow affects how the JIT operates. Hence, it is critical the exact program structure is used when testing for the problem.
<html>
<head>
<title>Array test page</title>
<script>
log = function(s) {
var ta = document.getElementById("ta");
ta.value += s + "\n";
}
function narrow(x_0) {
return x_0 << 24 >> 24;
}
function toStr(i8bytes) {
var bytes, i, str;
bytes = new Array(i8bytes.length);
str = '';
for (i = 0; i < 16; i++) {
bytes[i] = narrow(i8bytes[i]);
str += '*** (' + i8bytes[i] + ' - ' + bytes[i] + ')';
}
return str;
}
function doTest() {
var sz = 8192;
state = 0;
var i;
var fnd = false;
for (i = 0; i < 20; i++) {
var arr = new ArrayBuffer(sz);
var i8bytes = new Uint8Array(arr, 0, sz);
for (j = 0; j < i8bytes.length; j++) {
state = state + 1;
var v = state >> 8;
i8bytes[j] = narrow(v);
}
var str = toStr(i8bytes);
// log(str); <-- REMOVE COMMENT to show results
if (str.indexOf("NaN") !== -1) {
log("Found NaN at iteration" + i);
log(str);
fnd = true;
break;
}
}
return fnd;
}
function start() {
log("Starting: " + new Date());
if (!doTest()) {
location.reload(true); // <--- REMOVE THIS LINE TO PREVENT RELOAD
}
};
</script>
</head>
<body onload="start()">
<h1>Array test page</h1>
<p>Note that on a non-affected browser this page will reload indefinitely. On an affected browser, it
will stop reloading once the problem is detected.
<p>
<textarea id="ta" rows="10" cols="40"></textarea>
</body>
</html>
I'm facing a really strange problem comparing integer in Javascript. I have an array of numbers and I want to check if the current number in a loop is smaller than the previous one. To do so, I save the "current" number as "previous", so I can check them in the next loop. The function runs as expected, EXCEPT every time the current and the previous number have a different number of digits: in this case, the code doesn't see the actually smaller number as being smaller than the previous one.
For example:
111 < 120 ? ---> YES!
106 < 111 ? ---> YES!
98 < 106 ? ---> NO!
76 < 98 ? ---> YES!
5 < 76 ? ---> NO!
I'm unable to find anything strange in the code I'm using, as it is quite simple:
for(var j=0;j<arrScores.length;j++)
{
if(arrScores[j][0] < scoreAnt)
{
console.log("Smaller!");
}
scoreAnt = arrScores[j][0];
}
I've tried using parseInt() in both values, but nothing changes... Checking the length of both numbers using scoreAnt.toString().length returns a length of 1, no matter which number it is (100, 34 or 156798), and the same for arrScores[j][0]. I've also logged the whole thing to check that the numbers are the expected ones, and they are (the numbers used in the example are some of the ones I'm using)...
Any clue on what can be happening? I'm really lost with this, becuase it makes no sense for me...
Thanks in advance for your time and effort! :)
You always do scoreAnt = arrScores[j][0]; in the loop; but you should only do that if arrScores[j] is smaller; i.e. inside the inner curly braces.
for(var j=0;j<arrScores.length;j++)
{
if(arrScores[j][0] < scoreAnt)
{
console.log("Smaller!");
scoreAnt = arrScores[j][0];
}
}
Well, don't even know why, but after changing something relating the CORS of the server where these numbers came from (but not modifying the numbers at all), the comparison seems to work as expected... Have no clue about what might have changed! :S However, now it works correctly...