I am new to js and I want to calculate a sum in the array. The issue is that my array is sitting in object - game. Here is my code:
var game = {
fullName: 'Mark Visp',
score: [110, 320, 50, 80],
sumScore: function () {
this.total = [];
var total = 0;
for (i = 0; i < this.score.length; i++) {
total = total + this.score[i];
}
return total
}
}
game.sumScore();
console.log(game);
I am missing something?
Thanks in advance.
Please replace with below code
var game = {
fullName: 'Mark Visp',
score: [110, 320, 50, 80],
total: 0,
sumScore: function () {
var _total = 0;
for (i = 0; i < this.score.length; i++) {
_total = _total + this.score[i];
}
this.total = _total;
}
}
game.sumScore();
console.log(game);
Related
I am trying to create an array of sizes. I am adding to the array just fine and it is displaying. I try to remove with .pop(); and it gives me the error listed in the title of this post.
this.add = function(item, id, size){
var storedItem = this.items[id];
if(!storedItem) {
storedItem = this.items[id] = {item: item, qty: 0, price: 0, size: []}. <------
}
storedItem.size += size;
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.item.price;
}
this.reduceByOne = function(id){
this.items[id].size.pop(). <------------
this.items[id].qty--;
this.items[id].price -= this.items[id].item.price;
this.totalQty--;
this.totalPrice -= this.items[id].item.price;
if(this.items[id].qty <= 0) {
delete this.items[id];
}
}
I have also tried this and get the same error.
var reduceOne = this.items[id].size;
reduceOne.pop();
storedItem.size += size;
Did you mean to use push here instead of +=?
storedItem.size.push(size);
I'm attempting to get a list of all groups and all members of a group to be posted to a spreadsheet titled 'allGroups'. However, whenever I try to print the Array to the sheet I'm getting the error that says I can't convert the Array to an Object.
I've tried setting the array to be different sizes, changing the range so that it's more specific, and changing the code so that the group name is posted first (clearing the Array) and then moving from there but it hasn't worked.
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'google.com',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push(member.email);
outputSheet.getRange(u+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
}
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
Expected results would be that a list of groups would populate across row 1, and the list of member's emails would appear below each group. Currently once I get to
outputSheet.getRange(u+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
it tells me that can't convert the Array to an Object and fails.
EDIT
I've managed to get it working thanks to AMolina, Ross, and Cooper. This is the code I've got now:
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
var p = 0;
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'google.com',
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push([member.email]);
}
if(membersPageToken != undefined) {
p = p + 200;
} else { p = 0; }
Logger.log(p);
outputSheet.getRange(p+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
It also is able to handle when there's more than 200 members in a group.
Try this:
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'sbtagent197.eu',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push([member.email]);
}
// This is where I made the change, moving this line outside the inner loop.
outputSheet.getRange(1, i+1, listArray.length, listArray[0].length).setValues(listArray);
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
I modified the code you had by changing the location of the outputSheet.getRange(1, i+1, listArray.length, listArray[0].length).setValues(listArray); line, you were calling it several times during the loop, which was causing the title to appear many times. basically, you were writing the block of group_name -> members over and over, one row lower every time, so it looked like you were writing the title a bunch of times when it was the whole thing.
The edited code sets the values once when the array is complete, it will write the name of the group in the first row and the members in the rows below it. Moving forward I would suggest you consider #Cooper 's advice, using getValues() and setValues() can make working with sheets much easier.
For some reason, the else clause in my conditional rewrites the value in the array even when it finds a match. Any idea why this is happening? Code below:
controller.js
$scope.allAds = DummyAdService.dummyAds;
$scope.allStatements = DummyStatementsService.dummyStatements;
for(var i=0; i < $scope.allStatements.length; i++) {
var statement = $scope.allStatements[i];
for(var j=0; j < $scope.allAds.length; j++) {
var ad = $scope.allAds[j];
if(statement.statement.toLowerCase().indexOf(ad.tag) > -1) {
statement.ad = ad.url;
} else {
var randomAd = $scope.allAds[Math.floor(Math.random() * $scope.allAds.length)];
statement.ad = randomAd.url;
}
}
};
services.js
function DummyStatement(id, accountId, reportId, timestamp, rating, statement, url) {
this.id = id;
this.accountId = accountId;
this.reportId = reportId;
this.timestamp = timestamp;
this.rating = rating;
this.statement = statement;
this.url = url;
}
function DummyStatementsService(DummyAccountService) {
this.dummyStatements = [
new DummyStatement(1, 1, 1, 1449635098000, 'pos',
'Time to visit my second home. Gym haha'),
new DummyStatement(2, 1, 1, 1449615098000, 'pos',
'Feeling so much better after 10 hours sleep'),
new DummyStatement(3, 1, 1, 1440615028000, 'pos',
'Excited about going to Thorpe Park tomorrow'),
new DummyStatement(16, 2, 1, 1449635098000, 'neg',
'What a terrible week it\'s been so far. Weekend can\'t come soon enough'),
new DummyStatement(17, 2, 1, 1449615098000, 'neg',
'Rain rain rain go away. We all want some sunshine'),
new DummyStatement(18, 2, 1, 1440615028000, 'neg',
]
}
function DummyAd(id, tag, url) {
this.id = id;
this.tag = tag;
this.url = url;
}
function DummyAdService() {
this.dummyAds = [
new DummyAd(1, "gym", "ad-gym.jpg"),
new DummyAd(2, "sleep", "ad-sleep.jpg"),
new DummyAd(3, "thorpe park", "ad-themepark.jpg"),
]
}
Fixed it by adding statement = $scope.allStatements[i+1].
if(statement.statement.toLowerCase().indexOf(ad.tag) > -1) {
statement.ad = ad.url;
statement = $scope.allStatements[i+1];
} else if(statement.statement.toLowerCase().indexOf(ad.tag) === -1) {
var randomAd = $scope.allAds[Math.floor(Math.random() * $scope.allAds.length)];
statement.ad = randomAd.url;
}
I'm making a game currently for fun, and wanted to use arrays to draw levels with.
However, it seems there is some error that stops the program from actually drawing the rectangles. I've looked for pretty much every error that I could think of in the code. I've even tried re-learning the array subject on KhanAcademy, but nothing there seems to fix my problem. So I thought that StackOverflow was my last resort. You can see the game here, or if you just wanna see the pure code, it can be found here, and if you think my site will give you a virus, you can just see it here:
var sketchProc = function(processingInstance) {
with (processingInstance) {
size(400, 400);
frameRate(60);
// Setup stuff 'n stuff
noStroke();
fill(0, 0, 0);
var scene = 0;
var controlsEnable = 0;
var tufdasDebug = 0;
var tufdasLeve;
/* Key/control variables (JavaScript key codes:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes)*/
var keyIsPressed = 0;
var key_SHIFT = 16;
var key_CTRL = 17;
// Position & Size variables
var jumperXPos = 100;
var jumperYPos = 360;
var jumperSize = 20;
// Counters
var jumperXCounter = 11;
var jumperYCounter = 11;
var shiftCounter = 11;
keyPressed = function() {
keyIsPressed = 1;
};
keyReleased = function() {
keyIsPressed = 0;
resetCounters();
};
var askForResolution = function() {
text("What resolution do you want to play in?", 100, 15);
};
var addCounters = function(amount) {
if (amount) {
jumperXCounter += amount;
jumperYCounter += amount;
shiftCounter += amount;
} else {
jumperXCounter ++;
jumperYCounter ++;
shiftCounter ++;
}
};
var resetCounters = function() {
jumperXCounter = 11;
jumperYCounter = 11;
shiftCounter = 11;
};
var controlsHandler = function() {
addCounters();
if (tufdasDebug === 1) { console.log("Handling controls..."); }
if (keyIsPressed === 1) {
if (tufdasDebug === 1) { console.log("A key is being pressed..."); }
if (controlsEnable === 0) {
if (tufdasDebug === 1) { console.log("Controls disabled..."); }
if (keyCode === key_SHIFT) {
if (tufdasDebug === 1) { console.log("Shift is being pressed."); }
scene ++;
controlsEnable = 1;
}
} else if (controlsEnable === 1) {
if (keyCode === UP && jumperYCounter > 10) {
jumperYPos -= 20;
jumperYCounter = 0;
} else if (keyCode === RIGHT && jumperXCounter > 10) {
jumperXPos += 20;
jumperXCounter = 0;
}
}
}
};
var drawIntroSequence = function(y) {
textSize(30);
text("JUMPER", 125, y + 100);
textSize(15);
text("Press SHIFT or RSHIFT to continue...\n(make sure to click inside the game first)", 65, y + 300);
};
var drawJumper = function() {
fill(0, 0, 255);
rect(jumperXPos, jumperYPos, jumperSize, jumperSize);
};
var drawtufdasLevel = function() {
fill(0, 0, 0);
rect(tufdasLevel[0], tufdasLevel[1], tufdasLevel[2], tufdasLevel[3]);
rect(tufdasLevel[4], tufdasLevel[5], tufdasLevel[6], tufdasLevel[7]);
};
draw = function() {
background(255, 255, 255);
if (scene === 0) {
drawIntroSequence(0);
var tufdasLevel = [0, 380, 400, 20, 0, 0, 400, 20]; // Space indicates a new command.
} else if (scene === 1) {
drawtufdasLevel();
drawJumper();
}
controlsHandler();
};
}};
var canvas = document.getElementById("tufdaDrawCanvas");
var processingInstance = new Processing(canvas, sketchProc);
To figure out exactly what's happening, open up your JavaScript console by opening your game in a browser, pressing the F12 key, and then going to the "Console" tab.
When your game starts, you'll see the error:
Uncaught TypeError: Cannot read property '0' of undefined at game.js:100
That tells you the error is happening on line 100 of your sketch, which is this line:
rect(tufdasLevel[0], tufdasLevel[1], tufdasLevel[2], tufdasLevel[3]);
So now you know something is wrong with your tufdasLevel variable. Let's see where you declare it. You've got one here on line 12:
var tufdasLevel;
That's your declaration, but where is your initialization? You've got one here, one line 118:
var tufdasLevel = [0, 380, 400, 20, 0, 0, 400, 20]; // Space indicates a new command.
Ah-ha! Notice how you're using the var keyword to declare another variable named tufdasLevel. This is a different variable from the one at the top of your sketch, which is the one being used on line 100. The tufdasLevel variable on line 118 is never used, and the tufdasLevel on line 12 is never initialized. So when your game tries to use that uninitialized variable, you get the error you're seeing.
It seems like you meant to initialize the variable on line 118, not declare it. Try just dropping the var keyword from line 118:
tufdasLevel = [0, 380, 400, 20, 0, 0, 400, 20]; // Space indicates a new command.
You might also put that initialization on line 12 instead.
I am trying to answer my own unanswered question but stuck with some weird results of my code that I can't figure out.
When I generate the whole table by entering common heights and floor numbers and then add Elevators one by one The program works fine and perfect.
But When I add some rows manually by clicking arrow signs and then add elevator, instead of adding one elevator it adds many elevators, where number of elevators = number of floors manually added.
I tried to look at code line by line, but I can't figure out, where is bug here. Please support!
My concern is problems in one of following functions mostly $scope.AddElevator
$scope.AddElevator = function(ElevatorName) {
console.log("Floor Numbers");
console.log($scope.Floors.length);
/* $scope.Floors.sort(function(a, b) {
if (a.FloorNo > b.FloorNo) {
return -1;
}
if (a.FloorNo < b.FloorNo) {
return 1;
}
// a must be equal to b
return 0;
});
*/
// CODE to ADD New Elevator in Table
for (var i = 0; i < $scope.Floors.length; i++) {
console.log(i);
$scope.Floors[i].LiftServeDetails.push({
Name: ElevatorName,
ASide: "Available",
BSide: "N/A"
});
console.log($scope.Floors[i]);
}
};
// Add Row on top of a Row
$scope.floorUp = function(floorno) {
$scope.tmpLiftServeDetails = [];
$scope.tmpLiftServeDetails = $scope.Floors[0].LiftServeDetails;
for (var i = 0; i < $scope.Floors.length; i++) {
if ($scope.Floors[i].FloorNo > floorno) {
$scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
}
}
$scope.Floors.push({
FloorNo: floorno + 1,
Level: null,
Height: 0,
Shops: 0,
LiftServeDetails: $scope.tmpLiftServeDetails
});
};
// Add Row in bottom of a Row
$scope.floorBottom = function(floorno) {
$scope.tmpLiftServeDetails = [];
$scope.tmpLiftServeDetails = $scope.Floors[0].LiftServeDetails;
for (var i = 0; i < $scope.Floors.length; i++) {
if ($scope.Floors[i].FloorNo >= floorno) {
$scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
}
}
$scope.Floors.push({
FloorNo: floorno,
Level: null,
Height: 0,
Shops: 0,
LiftServeDetails: $scope.tmpLiftServeDetails
});
};
In your floorUp and floorBottom function you are not copying the objects, you are referencing them.
Try this:
$scope.floorUp = function(floorno) {
var tmpLiftServeDetails = angular.copy($scope.Floors[0].LiftServeDetails);
for (var i = 0; i < $scope.Floors.length; i++) {
if ($scope.Floors[i].FloorNo > floorno) {
$scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
}
}
$scope.Floors.push({
FloorNo: floorno + 1,
Level: null,
Height: 0,
Shops: 0,
LiftServeDetails: tmpLiftServeDetails
});
};