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);
Related
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.
I have this code in my simple flash. I want to save name and score in my quiz. My code reference in this website http://www.mollyjameson.com/blog/local-flash-game-leaderboard-tutorial/
I want to make my code in just one actionscript. But I didn't success do it.
var m_FlashCookie = SharedObject.getLocal("LeaderboardExample");
var EntryName:String ="nama kamu";
var EntryScore:String ="nilai";
const NUM_SCORES_SAVED:int = 10;
inputBoxScore.text = EntryScore;
inputBoxName.text = EntryName
var latest_score_object:Object = {
name: EntryName,
score: EntryScore
};
var arr:Array;
arr = m_FlashCookie.data.storedArray
if ( arr == null)
{
arr = new Array();
}
arr.push( latest_score_object );
arr.sortOn("score", Array.NUMERIC | Array.DESCENDING);
if ( arr.length < NUM_SCORES_SAVED )
{
arr.pop();
}
btnSave.addEventListener(MouseEvent.CLICK, saveData);
function saveData(event:Event):void
{
m_FlashCookie.data.arr = arr;
m_FlashCookie.flush();
}
var myHTMLL:String = "";
var total_stored_scores:int = arr.length;
btnLoad.addEventListener(MouseEvent.CLICK, loadData);
function loadData(event:Event):void
{
for (var i:int = 0; i < total_stored_scores; ++i)
{
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var leaderboard_entry:Object = arr[i];
// is this the last score that was just entered last gamestate?
if ( leaderboard_entry == latest_score_object )
{
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ leaderboard_entry.name + " " + leaderboard_entry.score +"</font></b><br>";
}
else
{
myHTMLL += (i+1) + ". "+ leaderboard_entry.name + " " + leaderboard_entry.score +"<br>";
}
}
myHTML.text = myHTMLL;
}
Can anybody help me?
You're saving the array as data.arr but reading the array as data.storedArray. You need to make them the same.
In other words, you've written this:
m_FlashCookie.data.arr = arr;
And when you load:
arr = m_FlashCookie.data.storedArray;
This clearly doesn't make sense: data.storedArray is never set, so it will never have a value, so you will always end up with a new empty array.
You need to use the same property on the shared object data. For example:
m_FlashCookie.data.storedArray = arr;
m_FlashCookie.flush();
Looking at your code, there's a number of other issues:
The latest score is immediately removed because arr.length < NUM_SAVED_SCORES is going to be true from the start, since arr starts out empty, and it then calls arr.pop() which will remove the latest entry that was just added. So the array is always empty.
It adds the score immediately with arr.push(latest_score_object) instead of waiting until the user clicks save, so the value of the input texts don't matter at all -- the saved values will always be "nama kamu" and "nilai".
The following fixes all the issues mentioned:
var leaderboard = SharedObject.getLocal("leaderboard");
const MAX_SAVED_SCORES:int = 10;
inputBoxName.text = "nama kamu";
inputBoxScore.text = "nilai";
var entries:Array = leaderboard.data.entries || [];
var latestEntry:Object;
displayScores();
btnLoad.addEventListener(MouseEvent.CLICK, loadClick);
btnSave.addEventListener(MouseEvent.CLICK, saveClick);
function loadClick(e:MouseEvent):void {
displayScores();
}
function saveClick(e:MouseEvent):void {
saveLatestScore();
displayScores();
}
function saveLatestScore():void {
// create the latest entry based on input texts
latestEntry = {
name: inputBoxName.text,
score: inputBoxScore.text
};
// add the entry and sort by score, highest to lowest
entries.push(latestEntry);
entries.sortOn("score", Array.NUMERIC | Array.DESCENDING);
// if reached the limit, remove lowest score
if (entries.length > MAX_SAVED_SCORES) {
entries.pop();
}
// store new sorted entries to shared object
leaderboard.data.entries = entries;
leaderboard.flush();
}
function displayScores():void {
var myHTMLL:String = "";
for (var i:int = 0; i < entries.length; ++i) {
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var entry:Object = entries[i];
// is this the last score that was just entered last gamestate?
if (entry == latestEntry)
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ entry.name + " " + entry.score +"</font></b><br/>";
else
myHTMLL += (i+1) + ". "+ entry.name + " " + entry.score +"<br/>";
}
myHTML.htmlText = myHTMLL;
}
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.
There is a multi-d array and I want to reach specific field in it. I have look around it but I was unable to find proper answer to my question.
My array is like that;
array-md
columns-- 0 | 1 | 2
index 0 - [1][John][Doe]
index 1 - [2][Sue][Allen]
index 2 - [3][Luiz][Guzman]
.
.
.
index n - [n+1][George][Smith]
My question is how can I reach only second column of the array? I tried name = array[loop][1]; but it says "Cannot access a property or method of a null object reference". What is the right way to do that?
Here is main part of the code.
get
var lpx:int;
var lpxi:int;
var arrLen:int = Info.endPageArray.length;
for(lpx = 0; lpx < arrLen; lpx++)
{
for(lpxi = Info.endPageArray[lpx][2]; lpxi < Info.endPageArray[lpx][1]; lpxi++)
{
if(Info._intervalSearch[lpxi] == "completed")
{
successCount++;
Info._unitIntervalSuccess.push([lpx, successCount / (Info._intervalSearch.length / 100)]);
}
}
}
set
for(lpix = 0; lpix < arrayLength; lpix++)
{
if(lpix + 1 <= arrayLength)
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix + 1], Info._UnitsTriggers[lpix]]);
}
else
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix], Info._UnitsTriggers[lpix - 1]]);
}
}
Try this:
var tempArr:Array = [];
function pushItem(itemName:String, itemSurname:String):void
{
var tempIndex:int = tempArr.length;
tempArr[tempIndex] = {};
tempArr[tempIndex][tempIndex + 1] = {};
tempArr[tempIndex][tempIndex + 1][name] = {};
tempArr[tempIndex][tempIndex + 1][name][itemSurname] = {};
}
function getNameObject(index:int):Object
{
var result:Object;
if(index < tempArr.length)
{
result = tempArr[index][index + 1];
}
return result;
}
pushItem("Max", "Payne");
pushItem("Lara", "Croft");
pushItem("Dart", "Vader");
//
trace(getNameObject(0));
trace(getNameObject(1));
trace(getNameObject(2));
Multidimensional array is an array of arrays, which you can create like this :
var persons:Array = [
['John', 'Doe'],
['Sue', 'Allen'],
['Luiz','Guzman']
];
var list:Array = [];
for(var i:int = 0; i < persons.length; i++)
{
list.push([i + 1, persons[i][0], persons[i][1]]);
}
trace(list);
// gives :
//
// 1, John, Doe
// 2, Sue, Allen
// 3, Luiz, Guzman
Then to get some data :
for(var j:int = 0; j < list.length; j++)
{
trace(list[j][1]); // gives for the 2nd line : Sue
}
For more about multidimensional arrays take a look here.
Hope that can help.
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
});
};