How to declare a variable with no value? - javascript

The following code is what I am using to convert a hex to binary. To print binary out, I add individual strings to a previously declared blank variable. However, this prints out "undefined + binary". Is there a way to declare a variable with no value --even undefined. If not is there a better way to concatenate variables in a for loop without a previously declared variable?
All help will be appreciated!
var integer = prompt("Insert hex digit");
var userHexDigits = [];
var hexDigits = [0, 1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
var binaryDigits = ['0000', '0001','0010','0011', '0100','0101','0110','0111','1000','1001','1010','1011','1100','1101','1110','1111'];
var hexy = [];
var binary
for(i = 0; i < integer.length; i++) {
digit = i + 1;
document.write("Your digit #" + digit + " is: " + integer[i] + "<br/>");
userHexDigits.push(integer[i]);
}
for (var m = 0; m < userHexDigits.length; m++) {
hex = userHexDigits[m];
for(k =0; k < hexDigits.length; k++) {
if (hex == hexDigits[k]){
binary += binaryDigits[k] + " ";
}
}
}
document.write("<br/><br/>The number " + integer + " in binary is " + binary);

If you want a string variable with an empty value just:
var binary = "";

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?

Need to make a list of the outstanding GPA’s from the array Im making (GPA’s over 3.4). Prefer traditional loop solution over some ES6 function

I need help with getting a list of GPAs over 3.4. I was able to sort largest to smallest, average, and get min and max GPAs utilizing traditional approaches (not ES6).
<div id ="out"></div>
<script>
var gpas = [];
var thegpas = " ";
var total = 0
while (thegpas != "XXX")
{
thegpas = prompt("Enter gpas or XXX to Stop");
if(thegpas != "XXX"){
gpas.push(thegpas);
} else {
break;
}
}
for(var x = 0; x < gpas.length; x++)
{
a = gpas.sort((a,b)=>b-a);
total=total + parseFloat(gpas[x]);
b = total/gpas.length //parseFloat(total)/length;
var max = gpas[0];
var min = gpas[0];
for(var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
}
//need help with this part
//outstandingGPAs=0;
outstandingGPAs = [];
cutoff = 3.4;
if (gpas[x]>cutoff){
outstandingGPAs.push(parseFloat(gpas[x]));
}
out= "Largest to smallest " + a + "<br/>" + "GPAs average: " + b + "<br/>" + " Max and Min: " + max + ", " + min + "<br/>" + "Outstanding GPAs (greather than 3.4): " + outstandingGPAs ;
// alert(gpas[x]);
}
document.getElementById('out').innerHTML=out;
Current Output:
Best way to output a (not very long) array is the join function.
In your output, you should use:
out = "<whatever you put>" + outstandingGPAs.join();
Check this link for more explanation of the join function.
Since you are already looping over your gpas array you could save those that are over 3.4 while you do that.
You would do that within your existing loop, not afterwards.
const cutoff = 3.4;
let outstandingGPAs = [];
// ...
for (var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
// added to the existing loop
if (gpas[i] > cutoff) {
outstandingGPAs.push(gpas[i]);
}
}
The outer loop should not be there, as you just redo the same operation over and over again.
As you only push at most one value in outstandingGPAs after you have set it to the empty array, that result will be wrong.
There are several other similar issues going on...
Also, getting input with prompt is really not user-friendly. The way to do this, is using an input element, and let the user type all values freely, and go back and correct whenever they want, and when they are happy with it, they can press a button so the code can run on it.
Here is how that looks:
var calcButton = document.getElementById("calc");
var gpasInput = document.getElementById("gpas");
var outDiv = document.getElementById('out');
calcButton.addEventListener("click", function () {
var min = Infinity,
max = -Infinity,
total = 0,
gpas = [],
outstandingGPAs = [];
// Collect the input as an array of strings with number-related characters
var inputStrings = gpasInput.value.match(/-?\d+(\.\d+)?/g);
for (var i = 0; i < inputStrings.length; i++) {
var num = parseFloat(inputStrings[i]);
gpas.push(num);
if (num > 3.4) {
outstandingGPAs.push(num);
}
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
total += num;
}
var average = total / gpas.length;
gpas.sort((a, b) => b - a);
// lets also sort the outstanding GPAs
outstandingGPAs.sort((a, b) => b - a);
outDiv.innerHTML = "Largest to smallest " + gpas.join(", ") + "<br>"
+ "GPAs average: " + average + "<br>"
+ "Max and Min: " + max + ", " + min + "<br>"
+ "Outstanding GPAs (greather than 3.4): " + outstandingGPAs.join(", ");
});
Enter gpas values: <input id="gpas">
<button id="calc">Calculate</button><br>
<div id ="out"></div>
Here:
let theGpas = "";
let gpaArr = [];
while(theGpas != "XXX"){
theGpas = prompt("Enter GPAs. Enter XXX to stop.");
if(theGpas != "XXX"){
gpaArr.push(theGpas);
}
}
gpaArr = gpaArr.sort();
document.write("Largest to Smallest: "+gpaArr.join(",")+"<br/>");
function average(array){
var totalSum = 0;
for(var n in array){
totalSum += array[n];
}
return totalSum/array.length;
}
function moreThanArray(array, comparison){
var returnArr = [];
for(var z in array){
if(array[z]>comparison){
returnArr[returnArr.length] = array[z];
}
}
return returnArr;
}
const averageOf = average(gpaArr);
document.write("GPAs average: "+averageOf+"<br/>");
document.write("Max and Min: "+gpaArr[gpaArr.length-1]+", "+gpaArr[0]);
document.write("<br/>"+"Outstanding GPAs (greater than 3.4): "+moreThanArray(gpaArr, 3.4).join(","));

JavaScript - Printing from Array of Objects Not Working

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

Match a range of rows in an array? jQuery, Javascript

I'm unsure how else to write the title but it's about as close as I can get to what I'm after.
I have a calculator I'm trying to create that compares values in a number of arrays.
Each data object in my array has 34 rows, some of which have the same number/value in them.
At the minute if you select france, I only want 1 of each grade to show in the dropdown, so the number 1 would appear once.
If you select France and grade 1, I want the outputted value to say the lowest value in that range to the highest, in this case USA would output 3 to 5 does this make sense?
If so I'm wondering how I'd possibly do this?
JSFiddle
http://jsfiddle.net/R85Qj/
Does this help?
http://jsfiddle.net/R85Qj/2/
$("#convert").on("click", function () {
var gradeIndex = $("#grade").val();
var gradeConversion = "";
/* gradeConversion += "<span>" + countryGrades[countryGradesIndex].country + ": " + countryGrades[countryGradesIndex].grades[gradeIndex][1] + "</span>";*/
var indexes = [];
var countryIndex = $("#country").val();
var gradeValue = countryGrades[countryIndex].grades[gradeIndex][0];
// find all indexes of gradeValue
for(var i = 0; i < countryGrades[countryIndex].grades.length; i++) {
if (countryGrades[countryIndex].grades[i][1] == gradeValue) {
indexes.push(i);
}
}
allValues = [];
for(var c = 0; c < countryGrades.length; c++) {
gradeConversion += countryGrades[c].country + ":";
for(i = 0; i < indexes.length; i++) {
if (i == 0 || countryGrades[c].grades[indexes[i]][1] != countryGrades[c].grades[indexes[i-1]][1]) {
gradeConversion += countryGrades[c].grades[indexes[i]][1] + " ";
}
}
}
$("#conversions").html(gradeConversion);
});

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