Node.js code being skipped (for) - javascript

I cannot see what's happening here, can someone enlighten me?
Why am I not entering the FOR?
Code:
console.log('l:269');
var smallestPrice = itemPriceAll; // start with max
console.log('itemNames.length, itemPriceall: ' + itemNames.length + ' ' + itemPriceAll);
for (var y; y < itemNames.length; y++) {
console.log('Are you fucking kidding me?');
console.log('l:272, itemPrice: ' + itemPrice[y] + 'houseEdge: ' + (itemPriceAll * houseEdge));
if (itemPrice[y] >= (itemPriceAll * houseEdge)) {
console.log('l:274');
if (itemPrice[y] < smallestPrice) {
smallestPrice = itemPrice[y];
keeping = itemId[y];
}
}
}
console.log('l:284');
Output:
l:269
itemNames.length, itemPriceall 23 97
l:284

In your for loop, your condition is y < itemNames.length, but the initial value of y is undefined. Thus, the condition is falsy. If you want to do a numeric comparison, you should initialize y to a numerical value.
I'd suggest var y = 0.

for(var y = 0; y < itemNames.length; y++)
was it; I expected y to be empty and numeric.
Thanks to https://stackoverflow.com/users/4265939/neilsimp1

Related

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

How to create a function that will return a length (n) with multiples of (x)?

function countBy(x, n) {
var z = [];
for (i = 0; i < n; i++) {
z.push(z[i] + x);
}
return z;
}
The results I'm getting from the test code Test.assertSimilar(countBy(1,5), [1,2,3,4,5]) are [null,null,null,null,null]. I assume this is because the z array is initially empty. I've searched for some help on this problem but I can't seem to find any. Thank you!
// z is the variable you're building. `z[i]` does not exist yet.
z.push(z[i] + x);
// You want this..
z.push(i*x);
https://jsfiddle.net/9h911x28/
also, matter of preference, but you probably also want to start i out as 1 instead of 0.
for (i = 1; i <= n; i++)

Colon operator ":" before function call (javascript)

I was looking at the source to a website and I saw this strange href attribute in a link and I can't figure out what it's doing. It doesn't look like valid javascript. I thought maybe the colon operator here was being used as a way to access the function property popDocWin in the object javascript but when I tried to emulate that syntax on a test function it wouldn't work.
Exterior Adjustable
javascript: is a psuedo-protocol meaning "run the code following this." You can use it (in a browser context) anywhere a URL is valid. In this case, clicking the link "follows" the link, and the act of following the link runs the JavaScript rather than going anywhere. (This is also how bookmarklets work.) So the javascript: part of that isn't JavaScript, just the part after it.
However, something that looks like that is valid JavaScript: If it weren't in a URL, it would create a labelled statement. The primary use of labelled statements in JavaScript is breaking outer loops from within inner ones, like this:
var x, y;
outer: for (x = 0; x < 5; ++x) {
for (y = 0; y < 5; ++y) {
if (x === 2 && y === 3) {
break outer;
}
snippet.show("x = " + x + ", y = " + y);
}
}
Output:
x = 0, y = 0
x = 0, y = 1
x = 0, y = 2
x = 1, y = 0
Note how the x loop was terminated from within the y loop.
var snippet = {
show: function(msg) {
document.body.insertAdjacentHTML("beforeend", "<p>" + msg + "</p>");
}
};
var x, y;
outer: for (x = 0; x < 3; ++x) {
for (y = 0; y < 3; ++y) {
if (x === 1 && y === 1) {
break outer;
}
snippet.show("x = " + x + ", y = " + y);
}
}
The colon is not before the function call, its after the word javascript!
It is telling your browser it should execute the javasript code after the colon.
Well, href isn't a place where your browser would expect javascript code, so javascript: tells the browser that it should treat whatever is after it as javascript.

Adding dynamically to an empty string

I am trying to assign each character in a nonempty string to an empty string (making a copy). Here is my code:
x = "example";
y = "";
for (var i = 0; i < x.length; i++) {
y.charAt(i) = x.charAt(i);
}
alert(y);
However, I get the following error in the console:
ReferenceError: invalid assignment left-hand side
y.charAt(i) = x.charAt(i);
I thought it was possible to grow a non-empty string dynamically (hope i'm using the correct terminology). Any help is appreciated!
The "".charAt(0) in an empty string is not defined. Indeed, "a".charAt(0) is "a".
Why don't you concatenate?
x = "example";
y = "";
//Simplest way:
y += x;
//With characters:
for (var i = 0; i < x.length; i++) {
y += x.charAt(i);
}
charAt(x) returns a string containing a character at the position x of the string this, but does not return a link to that position, thus, it is not equal to C's [] notation which returns a link to a byte where the character is located.
So, the charAt(x)= assignment is not valid as well as "a"="b" isn't, too.
Anyway, you can't do "".charAt(x) no matter what is x, because the string is empty.
Anyway, you can't even do "a".charAt(0)="b", because of the reason described in the first paragraph.
So, the only way to change some character in a string is str[x], which works in most browsers. But you still can't ""[0]", so you should first create a string with the same length as the string you are copying, or use concatenation.
It is possible. This is the right way to go:
x = "example";
y = "";
for (var i = 0; i < x.length; i++) {
y += x.charAt(i);
}
Your approach is not correct, since the charAt(i) method returns the (read-only) value of the char at position i.
Instead, an assignment operator, such as =, stores the value on the right side of the op = into the variable on the left side.
In this case y += x.charAt(i) is equal to y = y + x.charAt(i).
e.g.:
1st iteration:
x = "example";
y = ""
i = 0
x.charAt(i) == x.charAt(0) == "e"
y += x.charAt(i) -> y = y + x.charAt(i) -> y = y + x.charAt(0) -> y = y + "e" -> y = "" + "e" = e
2nd iteration:
x = "example";
y = "e"
i = 1
x.charAt(i) == x.charAt(1) == "x"
y += x.charAt(i) -> y = y + x.charAt(i) -> y = y + x.charAt(1) -> y = y + "x" -> y = "e" + "x"
and so on...
At each step, the char at position i of of the string x is appended to the string y and in the end x === y.

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Categories

Resources