javascript array not defined - javascript

Working on a project for school and arrays are causing me a serious problem. They are returning the error:
Uncaught ReferenceError: oddNumbers is not defined.
I did exactly what every other question on this site asked and to no avail. You can see in the ScriptManager "class" (as I am used to Java and C#) the oddNumbers and evenNumbers can't be pushed into. Please tell me whats wrong.
var manager = new ScriptManager();
function enterNumber() {
var number = prompt("Enter a number");
if (manager.addNumber(number)) {
document.getElementById("even").innerHTML = manager.getEvenNumbers();
document.getElementById("odd").innerHTML = manager.getOddNumbers();
document.getElementById("sum").innerHTML = manager.sum;
document.getElementById("average").innerHTML = manager.average;
}
}
function ScriptManager() {
this.count = 0;
this.oddCount = 0;
this.evenCount = 0;
this.sum = 0;
this.average = 0;
this.oddNumbers = [];
this.evenNumbers = [];
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
evenNumbers.push(number);
evenCount++;
count++;
} else {
oddNumbers.push(number);
oddCount++;
count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
sum += oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
sum += evenNumbers[x];
}
average = sum / count;
return true;
};
this.getEvenNumbers = function() {
var stream = "";
var first = true;
for (var x = 0; x < evenCount; x++) {
if (!first) {
stream + ", ";
}
stream += String.valueOf(evenNumbers[x]);
if (first) {
first = false;
}
}
return stream;
}
this.getOddNumbers = function() {
return "bleh";
}
}

You need to use the this. prefix before all the object properties.
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
this.evenNumbers.push(number);
this.evenCount++;
this.count++;
} else {
this.oddNumbers.push(number);
this.oddCount++;
this.count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
this.sum += this.oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
this.sum += this.evenNumbers[x];
}
this.average = this.sum / this.count;
return true;
};

In javascript, you have to use this in front of member variables to access them. So:
oddNumbers.push(number);
needs to be:
this.oddNumbers.push(number);
And, similarly for all the other member variables.

Related

TypeError in JavaScript when setting the Y position

When running this code I currently getting the error "TypeError: Invalid value for y-coordinate. Make sure you are passing finite numbers to setPosition(x, y)." all of my functions do work are are declared properly. When I use a println and print out letYPos it prints out "NaN" but when I call the function again it prints out the correct value. Does anyone know how I can fix this or if there even is a way to fix this?
var count = 0;
var letYPos = 0;
var y = 3;
function testing()
{
var letXPos = 25;
letYPos += 75;
if (count == 6)
{
println("You have ran out of guesses, the correct anwser was: " + secretWord);
return;
}
var input = readLine("Enter your word: ");
if (input == null)
{
println("You have to enter a word! ");
return;
}
if (input.length != 5)
{
println("That is not a five letter word, please try again.");
return;
}
var x = 3;
for (var i = 0; i < input.length; i++)
{
if (input.includes(secretWord.charAt(i)))
{
var index = input.indexOf(secretWord.charAt(i));
}
if (index == 0) { yellow(3, y ) }
if (index == 1) { yellow(83, y ) }
if (index == 2) { yellow(163, y) }
if (index == 3) { yellow(243, y) }
if (index == 4) { yellow(323, y) } index = null;
}
for (var i = 0; i < input.length; i++)
{
if (input.charAt(i) == secretWord.charAt(i))
{
green(x, y);
}
x += 80;
}
y += 80;
for (var i = 0; i < input.length; i++)
{
for (var a = 0; a <= 5; a++)
{
var txt = new Text(input.charAt(a), font);
txt.setPosition(letXPos, letYPos);
add(txt);
letXPos += 80;
}
}
if (input == secretWord)
{
println("That's Correct, Congratulations!");
return;
}
count++;
setTimeout(testing, 100);
}

When i pass 1 into n i do not get [0,1] i get [1]?

This is Fibonacci Generator function that i have created but for some reason i can't seem to get the output for 1 = [0,1] . While it works alright for other conditions.If somebody can point me at what i am doing wrong here.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
return output;
}
}
console.log(bl(1));
return output had to be executed for all conditions so just execute it at end of your function.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
}
return output;
}
console.log(bl(1));

Javascript formatting of 10 or 11 digit phone numbers and recognizing a 1800 phone number

I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>

After pasting the following code, my browser crashed. Why?

After pasting the following code, my browser crashed. I have absolutely no idea why. I am a new to Javascript.
Here is my code:
var randarray = new Array();
var l = 0;
var flag;
var numofpost = 5;
function randomposts(json) {
var total = parseInt(json.feed.openSearch$totalResults.$t, 10);
for (i = 0; i < numofpost;) {
flag = 0;
randarray.length = numofpost;
l = Math.floor(Math.random() * total);
for (j in randarray) {
if (l == randarray[j]) {
flag = 1;
}
}
if (flag == 0 && l != 0) {
randarray[i++] = l;
}
}
document.write('<ul class="rp-menu">');
for (n in randarray) {
var p = randarray[n];
var entry = json.feed.entry[p - 1];
for (k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
var item = "<li>" + "" + entry.title.$t + "</li>";
document.write(item);
}
}
}
document.write('</ul>');
}
The increment of i in your first for loop is behind a condition, so if it never resolves to true, you'll have an infinite loop

Why does method return 0?

Using the object and methods below, why does console.log(FizzBuzzPlus.getFizzBuzzCount(20)) print 0?
var FizzBuzzPlus = {
isFizzBuzzie: function(a) {
if(a%5 === 0 || a%3 === 0) {
if (a%5 === 0 && a%3 === 0) {
return false;
}
return true;
} else {
return false;
}
},
isFizzBuzzieChecker: function(c) {
var theFizzBuzzes = [];
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
theFizzBuzzes += i + " ";
}
}
return theFizzBuzzes;
},
getFizzBuzzSum: function(b) {
var sum = 0;
for (var i = 0; i < b; i++) {
if (this.isFizzBuzzie(i)) {
sum += i;
}
}
return sum;
},
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
return count;
}
}
};
console.log(FizzBuzzPlus.isFizzBuzzieChecker(20));
console.log(FizzBuzzPlus.getFizzBuzzSum(20));
console.log(FizzBuzzPlus.getFizzBuzzCount(20));
Some may recognize that this is FizzBuzz from Codecademy. I'm playing with the object using their online JavaScript editor. The printed result of the method is always 0. It should be returning the amount of numbers between 0 and 20 that are divisible by 3 or 5, but not both 3 and 5.
At this point in your code you have your return statement inside your for loop:
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
return count; //<-- this return is INSIDE the for loop
}
}
Move that return outside the for loop:
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
}
return count;
}
Fiddle:http://jsfiddle.net/hVf9n/
You have the return statement inside the for loop, also there is a syntax error in isFizzBuzzieChecker, where the closing ) is missing in the if condition
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
}
return count;
}
Demo: Fiddle

Categories