I don't understand this Javascript? - javascript

Can someone walk me thru this example and why it prints 10? I see to be getting confused on the function in function aspect I think. Also what is the difference between var x = and x = ?
var x = 6;
var y = 4;
var a = function(b) {
return function(c) {
return y + b + c;
}
};
x = 2;
y = 5;
var fn = a(x);
x = 1;
y = 3;
var unknown = 5;
console.log(fn(unknown));

var x = 6;
var y = 4;
var a = function(b) {
return function(c) {
return y + b + c;
}
};
x = 2;
y = 5; // unnecessary, meant to confuse
var fn = a(x); // creates a closure, where b equals 2
x = 1; // unnecessary, meant to confuse
y = 3;
var unknown = 5;
console.log(fn(unknown)); // y=3,b=2,c=5, total = 10

Related

Extract last ","

This is my code
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join();
}
basicIO.write(convertToCurr(input));
context.log.INFO("log data");
}
These are my outputs
{"output":"R 1,000,000,.00","log":["log data"]}
{"output":"R 1,000,.00","log":["log data"]}
I need to exctract the last "," so that the amounts make sense
The most straightforward solution is to perform a String.prototype.replace() on the final join().
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join().replace(',.', '.');
}
console.log(convertToCurr(10000.75));
console.log(convertToCurr(10.01));
console.log(convertToCurr(1000));
console.log(convertToCurr(7002344));
It should be noted that replace() only replaces a single instance of the substring you provide it in the input string, but this doesn't matter here since ,. only appears in your output string one time.
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
var combinedString; // holds string value after join
if (z == 0) {
a = x / 3 - 1;
} else {
a = x / 3;
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
combinedString = vals.join(); // join array into string
return combinedString.replace(",.", "."); // replace ,. with .
}
console.log(convertToCurr(50000000.15));

Paradoxical Javascript Variable Defining

I am trying to calculate a maths question. It requires the use of variables within variables that loop around.
Here is my JavaScript Code:
var a = m+1;
var b = n+1;
var c = o+1;
var d = p+1;
var e = q+1;
var f = r+1;
var g = s+1;
var h = t+1;
var i = u+1;
var j = v+1;
var l = w+1;
var m = (1+b)/2;
var n = (a+c)/2;
var o = (b+d)/2;
var p = (c+e)/2;
var q = (d+f)/2;
var r = (e+g)/2;
var s = (f+h)/2;
var t = (g+i)/2;
var u = (h+j)/2;
var v = (i+l)/2;
var w = (j+12)/2;
function CalculateA() {
alert(a);
}
The HTML is just a button calling CalculateA() Function.
This results with undefined. Is there a way to properly calculate this or is it not possible with javascript or coding.
Edit
I relize now that this isn't working very well.
Also I ran it through excel with looping calculations and found the answer.
Thanks for all your help anyway.
https://drive.google.com/open?id=0B9I2lCue4HpLZEh3X0NGTUE4YXM
The Excel Calculation ^
You could give all variables a start value of zero to prevent NaN and then call the operations again until a is converging to 12.916666666666651.
function calc() {
a = m + 1;
b = n + 1;
c = o + 1;
d = p + 1;
e = q + 1;
f = r + 1;
g = s + 1;
h = t + 1;
i = u + 1;
j = v + 1;
l = w + 1;
m = (1 + b) / 2;
n = (a + c) / 2;
o = (b + d) / 2;
p = (c + e) / 2;
q = (d + f) / 2;
r = (e + g) / 2;
s = (f + h) / 2;
t = (g + i) / 2;
u = (h + j) / 2;
v = (i + l) / 2;
w = (j + 12) / 2;
console.log(a);
}
var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0,
ii, letter;
for (ii = 0; ii < 1000; ii++) {
calc();
}
for (ii = 1; ii <= 23; ii++) {
letter = (ii + 9).toString(36);
letter === 'k' || console.log(letter, window[letter]); // k is missing ...
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nothing is impossible in coding. it is returning undefined because 'a' is declared on top where m is not defined and it is "NaN" error -- Not a Number.
The variables end up depending onto each other, which means that your result will always be NaN.
Javascript tries to give you an exact result for the formula, which it can't. What you need for this math issue, is to replace the variables in each term with each other, to get to a result with only 1 variable - I don't think there's a way for you to do that in Javascript with less effort than doing it manually.

for loop works fine with console.log but not innerHTML?

hello i'm very new to javascript so forgive me if the answer seems obvious...
this is my code which is executed at the click of a button in the body
function q() {
var A = document.getElementById("time_one").value;
var B = document.getElementById("time_two").value;
var C = document.getElementById("post_number").value;
var D = (B - A) / C;
for ( var x = A; x < B; x = x + D ) {
document.getElementById("q_box").innerHTML = x + "<br />";
}
}
i'm pretty sure the error is in the for loop... the output is supposed to be a list of numbers between A and B. and changing the innerHTML = to innerHTML += hasn't worked either?
function q() {
var A = +document.getElementById("time_one").value;
var B = +document.getElementById("time_two").value;
var C = +document.getElementById("post_number").value;
var D = (B - A) / C;
for ( var x = A; x < B; x = x + D ) {
document.getElementById("q_box").innerHTML += x + "<br />";
}
}
You should convert the values in int and you should use +=
With innerHTML code inside the for loop you are always setting the value with the last time iterated value. Hence, you need to update your code to
for ( var x = A; x < B; x = x + D ) {
document.getElementById("q_box").innerHTML += x + "<br />";
}
OR
var y = "";
for ( var x = A; x < B; x = x + D ) {
y += x + "<br />";
}
document.getElementById("q_box").innerHTML = y;
I will recommend you to go for 2nd option, as it is better to set the updated value at once and not to extract the value and update for each iteration.

Javascript problems with a function not working (it converts fractions into decimals)

Let's say I have a string (like a fraction);
var num = "1/2";
Why does this work:
var y = num.split(' ');
if (y.length > 1) {
var z = y[1].split('/');
var a = (+y[0] + (z[0] / z[1]));
num = a;
} else {
z = y[0].split('/');
if (z.length > 1) {
a = (z[0] / z[1]);
num = a;
}
}
alert(num); //The alert box shows my variable now as a decimal.
And this doesn't:
function parseFractions(x) {
var y = x.split(' ');
if (y.length > 1) {
var z = y[1].split('/');
var a = (+y[0] + (z[0] / z[1]));
x = a;
} else {
z = y[0].split('/');
if (z.length > 1) {
a = (z[0] / z[1]);
x = a;
}
}
}
parseFractions(num); //Here I call my function.
alert(num);
//The alert box does not even show up. The fraction isn't converted into a decimal.
It's basically the same thing, the only difference is that in the 2nd one I tried to make that into a function so I don't have to repeat those lines of code every time I try to convert fractions into decimals.
So what am I doing wrong? Is what I am trying to accomplish possible with a function? Any light into this issue is appreciated!
the value of num is not updated, it is not passed by reference.
function parseFractions(x) {
var y = x.split(' ');
if (y.length > 1) {
var z = y[1].split('/');
var a = (+y[0] + (z[0] / z[1]));
x = a;
} else {
z = y[0].split('/');
if (z.length > 1) {
a = (z[0] / z[1]);
x = a;
}
}
return x;
}
num = parseFractions(num); //set num with the value return from the method
alert(num);
You need to return your value
Add a return to the end of your function
return x;
Adn then call the function with
alert(parseFractions(num)); //Here I call my function.

Using javascript vars as array key names

I'm making a grid of 18 x 9 and want to calculate the sizes for all possible boxes that could be placed on the grid.
I'm placing them in objects, but the line
var template_sizes_site[x + 'x' + y] = {};
Is failing. it seems I can't use variables AND a string to name key?
I want basically to say array['2x9']['width'] = 42; etc
What am I missing?
var template_sizes = {};
var site_width = 70;
var site_height = 70;
var site_margin = 20;
for (var y = 1; y <= 9; y++)
{
for (var x = 1; x <= 18; x++)
{
var template_sizes_site[x + 'x' + y] = {};
template_sizes_site[x + 'x' + y]['width'] = ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0));
template_sizes_site[x + 'x' + y]['height'] = ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0));
}
}
Remove the var from your first line in the body of your nested for loop:
var template_sizes = {};
var site_width = 70;
var site_height = 70;
var site_margin = 20;
for (var y = 1; y <= 9; y++)
{
for (var x = 1; x <= 18; x++)
{
template_sizes_site[x + 'x' + y] = {};
template_sizes_site[x + 'x' + y]['width'] = ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0));
template_sizes_site[x + 'x' + y]['height'] = ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0));
}
}
var is only for variables, not for properties:
var template = {}; // OK
var template_sizes_site[x + 'x' + y] = {}; // not allowed, no need
Also you'll need to initialise template_sizes_site if that wasn't a typo.
You did not initialize your variable template_sizes_site (is this meant to be template_sizes ?). Also you could shorten your initialization code a little like shown below.
var template_sizes = {},
template_sizes_site = {},
site_width = 70,
site_height = 70,
site_margin = 20;
for (var y = 1; y <= 9; y++) {
for (var x = 1; x <= 18; x++) {
template_sizes_site[x + 'x' + y] = {
'width': ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0)),
'height': ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0))
};
}
}
You need to change var template_sizes_site[x + 'x' + y] = {}; into template_sizes_site[x + 'x' + y] = {}; because your way creates local variable in scope and after leaving it (when loop goes to next time) data is becomes lost.
Also template_sizes_site is not initialized if it is all your code.

Categories