Registrer in array and new variable - arrays

I am trying to make a program where you can register expenses on someone.
i have 2 TextInputs, named "txt1" and "txt2"
I want to make an eventlistener where
If you put in a new name in “txt1”, it will be registered in an array, and a new variable will be created, and the number in “txt2” will be added to that variable.
If you put in a name that’s already in the array, the number in “txt2” will be added the variable which was created when you typed in the name the first time.
Here's what i got so far
var names:Array = new Array();
stage.addEventListener(KeyboardEvent.KEY_DOWN, regi)
function regi(evt)
{
if (evt.keyCode == 13)
{
var k:String = txt1.text
if (names.indexOf(k) != -1)
{
txt1.text+txt2.text
}
else
{
names[names.length] = k
var txt1.text = txt2.text
}
}
}

you can use Dictionary to do that ex:
var names:Dictionary = new Dictionary();
stage.addEventListener(KeyboardEvent.KEY_DOWN, regi);
function regi( evt:KeyboardEvent ):void
{
if (evt.keyCode == 13)
{
if( names[txt1.text] ) names[txt1.text] += txt2.text;
else names[txt1.text] = txt2.text;
}
}

Related

localStorage Array Objects - How to check is Object Key Value exists

How would i check to see if the ID exists within the localStorage object key array
i am currenty using this and it does not work
if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }
Also how do i pull the indivdual object array apart into ID , image , title
to make varibles
Thank you
Below is the Full Code
function checkfave (theid) {
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage'+theid).attr('src');
var thetitle = $('#thetitle'+theid).text();
if (localStorage.getItem('favorites') != null) {
if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }
}
favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
localStorage.setItem('favorites', JSON.stringify(favorites));
alert('You Just Added Listing '+theid+' To Your Favorites');
//Loop through the Favorites List and display in console (HIDDEN)
console.clear();
for (let i = 0; i < favorites.length; i++) {
console.log('ID= '+favorites[i].ID+' IMAGE='+favorites[i].IMAGE+' TITLE='+favorites[i].TITLE);
}//for loop
}
When you parse json using JSON.parse, a javascript object is created. You can access keys in javascript objects by simply using the bracket notation:
object[key] = value
If a key is not defined in an object, when you request the key you will get undefined. undefined is equivalent to false when evaluating an if clause so you can simply use
if (favorites[theid]) { alert('You Allready Added this Listing'); }
I found a solution after the suggestions
My solution was to check within a for loop using favorites[i].ID == theid
The final code is below. i am very sure it could be done another way, But this works for now.
function checkfave (theid) {
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage'+theid).attr('src');
var thetitle = $('#thetitle'+theid).text();
var added=true;
//Loop through the Favorites List and display in console (HIDDEN)
for (let i = 0; i < favorites.length; i++) {
if ( favorites[i].ID == theid ) { alert('You allready Added Listing '+theid+' To Your Favorites'); var added=false; break; } else {var added=true;}
}//for loop
if (added===true) {
favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
localStorage.setItem('favorites', JSON.stringify(favorites));
alert('You Just Added Listing '+theid+' To Your Favorites');
}
}

How to get rid of "undefined" in Discord embeds

I'm trying to make it so that the output of this Discord embed won't be "undefined" for the Bot, Mute, and Deafen part of the embed.
I tried to change some var to "let" or "const"
I've tampered with the aboutuser portion to change it to something different.
I've messed with the if portion of the code.
Here's the code.
async run(message, args){
if (message.channel instanceof discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
var serv = message.guild
if (serv.explicitContentFilter == 0) {
var eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
var eFC = "Scan for users without a role.";
}
if (serv.explicitContentFilter == 2) {
var eFC = "Scan every message";
}
///////////////////////////////////////////////////////////////////////////////////////////////////
if (serv.verificationLevel == 4) {
var verL = "Intense (Verified Account & Verified Phone linked)";
}
if (serv.verificationLevel == 3) {
var verL = "Secure (Verified Account & Guild member for 10+ minutes)";
}
if (serv.verificationLevel == 2) {
var verL = "Medium (Verified Account for 5 minutes+)";
}
if (serv.verificationLevel == 1) {
var verL = "Low (Verified Account)";
}
if (serv.verificationLevel == 0) {
var verL = "None (No Restriction)";
}
//////////////
if (serv.region == `brazil`) {
var regio = "Brazil";
}
if (serv.region == `eu-central`) {
var regio = "Central Europe";
}
if (serv.region == `hongkong`) {
var regio = "Hong Kong";
}
if (serv.region == `japan`) {
var regio = "Japan";
}
if (serv.region == `russia`) {
var regio = "Russia";
}
if (serv.region == `singapore`) {
var regio = "Singapore";
}
if (serv.region == `southafrica`) {
var regio = "South Africa";
}
if (serv.region == `sydney`) {
var regio = "Sydney";
}
if (serv.region == `us-central`) {
var regio = "Central US";
}
if (serv.region == `us-east`) {
var regio = "East US";
}
if (serv.region == `us-south`) {
var regio = "South US";
}
if (serv.region == `us-west`) {
var regio = "West US";
}
if (serv.region == `eu-west`) {
var regio = "West Europe";
}
//
if (serv.defaultMessageNotifications == `ALL`) {
var defn = "Send all Messages";
}
if (serv.defaultMessageNotifications == `MENTIONS`) {
var defn = "Only #everyone";
}
var myInfo = new discord.RichEmbed()
.setAuthor(`${serv.name}'s guild info`,`${message.guild.iconURL}`)
.addField(`AFK Channel`,`${serv.afkChannel}`,true)
.addField(`AFK Timeout`,`${serv.afkTimeout}s`,true)
.addField(`Channels`,`${serv.channels.size}`,true)
.addField(`Creation of Guild`,`${serv.createdAt}`,true)
.addField(`Default Notification`, defn,true)
.addField(`Explicit Content Filter Level`, eFC,true)
.addField(`Guild ID`,`${serv.id}`,true)
.addField(`How much members`,`${serv.memberCount}`,true)
.addField(`Owner`,`${serv.owner}`,true)
.addField(`Region`, regio,true)
.addField('Roles', `Please do s!roles to find server roles!`, true)
/* serv.roles.map(r => `${r}`).join(' | ') */
.addField(`Verification Level`, verL,true)
.setColor(0x511fdd)
.setFooter('Aboutserver command')
.setThumbnail(`${message.guild.iconURL}`)
message.channel.sendEmbed(myInfo);
}
}
expected result : The bot will say Yes or No instead of undefined, or true or false.
actual result : The bot's output is just undefined.
There are a couple of things happening here, but let's focus on the main issue; how you have declared your variables.
To put it simply, variables can only be accessed within the scope in which they are declared in (The scope is all the code between the {}).
I'll explain it with a short example based on your code. In your if statements you declare your variables, meaning they can be used within that if statements' scope. You later want to use those same variables outside of the if statement and in your embed. Because those variables don't exist in that scope, they are undefined.
...
// At this point there is no variable 'eFC' available.
if (serv.explicitContentFilter == 0) {
// Here you create the variable 'eFC' but it can only be used inside this scope, meaning it cannot be accessed outside the 'if' statement.
var eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
// Here you create another variable with the same name, but it would end up being a different variable.
var eFC = "Scan for users without a role.";
}
// Here there is still no variable 'eFC' available to us.
...
The simple solution is: declare your variables in another scope and assign the values later. Below you can see an example:
...
// Here we create a new variable called 'eFC' which can be used within this scope
var eFC;
if (serv.explicitContentFilter == 0) {
// Here we assign a value to the previously defined variable
eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
// Here we assign a value to the previously defined variable
eFC = "Scan for users without a role.";
}
// Here we can use the variable 'eFC' which will have a value
console.log(eFC);
...
If you do this for all the variables which you use, the code should work fine.
Lastly I want to leave you with some extra help. I see you have created many, many, many if statements to check for e.g. the server region or the server verification level. Javascript (among many other programming languages) has a think called a switch case which basically does the same thing you have with all those if statements, but in a more neater way. Check out the link, I think it will help you make your code look a bit more readable

AngularJS Filter on nested properties

I would like to create a filter on nested objects like this:
Object 1 :
property1
property2
property3
children : Child 1 :
propertyChild1
propertyChild2
Child 2 :
And so on. An object can have multiple child. There is no depth limit specified.The problem is that I want to search only on certain properties of the object so I used:
ng-repeat="groupLevel1 in groupLevel2.children | filter: {lineDescription: searchKeyword}"
This is searching on all levels but if a parent does not contain the searchKeyword, all the children (which may contain the search) aren't displayed. I want that all parent levels are displayed in order to display the children that contains the search keyword even if the parents do not match the search.
I tried some complicated script but it does not work:
appReportingHoliday.filter('globalFilter', function(){
return function(array, predicate){
return array.filter(function(val){
var formattedObj = parseFloatInternational(predicate);
var re = new RegExp(formattedObj, 'i');
var initialArray = [];
initialArray.push(val);
var childIsNeeded = false;
var toReturnTemp;
var parents = [];
var toReturn = [];
while(initialArray!=null){
angular.forEach(initialArray, function (currentVal) {
toReturnTemp = false;
//We check if the val is concerned by the search
toReturnTemp = re.test(currentVal.lineDescription) || re.test(currentVal.acquiredHolidays) || re.test(currentVal.tokenHolidays) || re.test(currentVal.availableHolidays)
|| re.test(currentVal.dailyCost) || re.test(currentVal.valuation);
if (toReturnTemp) {
//if it is, we need to add the result to the toReturn array and also the parents that we could have saved in the according array
toReturn.push(currentVal);
toReturn.push(parents);
parents = [];
}
else {
//else we save it in the parents array if a child is needed
if(currentVal.children!=null) {
parents.push(currentVal);
}
}
var index = initialArray.indexOf(currentVal);
initialArray.splice(index, 1);
if(currentVal.children!=null) {
angular.forEach(currentVal.children, function (currentChild) {
initialArray.push(currentChild);
});
}
});
if(initialArray.length==0) initialArray = null;
}
return toReturn;
});
}
});
The display is made like this:
<tr class="groupReportingTreeDatatable" ng-repeat-start="groupLevel3 in myData | filter: {lineDescription: searchKeyword}" ng-init="$index < 2 ? groupLevel3.hideRows = false : groupLevel3.hideRows = true;" ng-class-even="'dataTable_row1'" ng-class-odd="'dataTable_row2'" spinner-handler-directive="">
...
<tr class="groupReportingTreeDatatable" ng-hide="groupLevel3.hideRows" ng-init="groupLevel2.hideRows = true" ng-repeat-start="groupLevel2 in groupLevel3.children | filter: {lineDescription: searchKeyword}" ng-class-even="'dataTable_row1'" ng-class-odd="'dataTable_row2'">
...
<tr ng-hide="groupLevel2.hideRows || groupLevel3.hideRows" ng-repeat="groupLevel1 in groupLevel2.children | filter: {lineDescription: searchKeyword}" ng-class-even="'dataTable_row1'" ng-class-odd="'dataTable_row2'" ng-repeat-end="">
EDIT :
I tried something else which works for some searches but not all of them :(
appReportingHoliday.filter('globalFilter', function() {
return function (array, predicate) {
return array.filter(function (val) {
var formattedObj = parseFloatInternational(predicate);
var re = new RegExp(formattedObj, 'i');
var found = re.test(val.lineDescription) || re.test(val.acquiredHolidays) || re.test(val.tokenHolidays) || re.test(val.availableHolidays)
|| re.test(val.dailyCost) || re.test(val.valuation);
var child = val.children;
while(child!=null && found == false){
angular.forEach(child, function (currentChild) {
if(found == false) {
console.log(currentChild.lineDescription)
found = re.test(currentChild.lineDescription) || re.test(currentChild.acquiredHolidays) || re.test(currentChild.tokenHolidays) || re.test(currentChild.availableHolidays)
|| re.test(currentChild.dailyCost) || re.test(currentChild.valuation);
}
});
child = child.children;
}
return found;
});
}
});
Wouldn't it be easier to have a second variable where you flatten all of the children of the first one? You could define a recursive function doing that, something like...
var mainObject = ... ;//that's your object
var flattened = new Array();
function flatten(main,flat) {
var children = main.children;
for (var i=0;i<children.length;i++) {
flatten(children[i],flat); // recursive call, depth-first
delete children[i].children; // those are already treated
flat.push(children[i]); // add children
}
delete main.children;
flat.push(main);
}
Now you can filter on the properties directly.
I don't see how to integrate this in my code. I cannot change the base variable because I need it in this structure to display it on the screen. I can create another flattened array but the filter has to be applied on the var I display, no ? So I cannot use the flattened var. I have to admit I am a bit lost ^^
I fixed the depth to 3 to make it easier so now I have a this:
appReportingHoliday.filter('globalFilter', function() {
return function (array, predicate) {
return array.filter(function (val) {
var formattedObj = parseFloatInternational(predicate);
var re = new RegExp(formattedObj, 'i');
var found = re.test(val.lineDescription) || re.test(val.acquiredHolidays) || re.test(val.tokenHolidays) || re.test(val.availableHolidays)
|| re.test(val.dailyCost) || re.test(val.valuation);
var child = val.children;
if(child!=null && found == false){
angular.forEach(child, function (currentChild) {
if(found == false) {
found = re.test(currentChild.lineDescription) || re.test(currentChild.acquiredHolidays) || re.test(currentChild.tokenHolidays) || re.test(currentChild.availableHolidays)
|| re.test(currentChild.dailyCost) || re.test(currentChild.valuation);
}
if(currentChild.children!=null && found == false){
angular.forEach(currentChild.children, function (currentGrandChild) {
if(found == false) {
found = re.test(currentGrandChild.lineDescription) || re.test(currentGrandChild.acquiredHolidays) || re.test(currentGrandChild.tokenHolidays) || re.test(currentGrandChild.availableHolidays)
|| re.test(currentGrandChild.dailyCost) || re.test(currentGrandChild.valuation);
}
});
}
});
child = child.children;
}
return found;
});
}
});
The only problem that remains is that if the search is on a parent, I want all the child t be displayed but right now only the matched children are displayed :s I cannot find the parent from a child, I have only the link from parent to child not the other way around :s

Using variable A to control variable B

I have a function called FarmClick, and I want it to check the current MovieClip's array. For example:
var farmSpot1:("id",int,int);
var farmSpot2...
I need the clickEvent to capture the MovieClips name and check it's array for the 0th element to see whether it's empty, or not...
My code so far:
public function FarmClick(event: MouseEvent): void {
var CurrentSlot = event.currentTarget.name
if ([event.currentTarget.name[0]] = "empty") {
stage.addChild(menu);
menu.x = 400;
menu.y = 90;
this.menu.buyCornBtn2.addEventListener(MouseEvent.CLICK,buyCorn2);
} else if (farmEmpty == true && itemSelected != "none") {
selected();
} else if (farmEmpty == false) {
farmHarvest();
}
}
It took me a minute to figure out just exactly what it was that you're asking.
So basically, your movie clip's name would be farmSpot[someNumber] and you have an array with the same name?
in that case, to reference the array variable, you need to use the this keyword.
you can add any array subscripts after you've referenced it like so:
private var farmSpot1:Array = ["id", int, int];
public function FarmClick(event:MouseEvent): void
{
if (this[event.currentTarget.name][0] == "") // wasnt sure if you meant the string "empty" or just an empty string, so i just put an empty string
{
// do whatevs
}
}

AS3 flash, Array objects are carrying over into next frame and causing null object error

//I commented out the section that I was trying, but so far nothing has been working. I know I need to set up a loop or something of that kind to get rid of the items in the array, but I'm not sure how to get the right outcome.
THANKS SO MUCH
import flash.utils.Timer;
import flash.display.MovieClip;
import flash.events.Event;
var loveXCounter: Number = 0;
healthLove_txt.text = "Wrong Words: 0";
var insideLoveXCount = new Timer(4000, 0)
insideLoveXCount.addEventListener(TimerEvent.TIMER, countLoveX);
insideLoveXCount.start();
var loveXList: Array = ["Hate", "Abhor", "Vile", "Dislike", "Enmity", "Illwill", "Loath", "Neglect", "Repulse", "Resent"];
function countLoveX(e: TimerEvent) {
var loveXName: String = loveXList[Math.floor(Math.random() * loveXList.length)];
var loveXReference: Class = getDefinitionByName(loveXName) as Class;
var myLoveX = new loveXReference;
myLoveX.x = Math.random() * 700;
myLoveX.y = -10;
myLoveX.speed = 5;
myLoveX.addEventListener(Event.ENTER_FRAME, fallingLoveX);
addChild(myLoveX);
loveXList.splice(loveXName, 1);
}
function fallingLoveX(e: Event): void {
if (e.target.hitTestObject(fb_mc)) {
e.target.visible = false;
loveXCounter = loveXCounter + 1;
e.target.removeEventListener(Event.ENTER_FRAME, fallingLoveX);
healthLove_txt.text = "Wrong Words: " + loveXCounter;
if (loveXCounter == 5) {
while( loveXList.length > 0 )
{
this.removeChild( loveXList[loveXList.length - 1] );
loveXList.pop();
}
MovieClip(root).gotoAndStop(137);
loseBook_mc.gotoAndStop("loseLove");
}
}
if (e.target.y < 800) {
e.target.y += e.target.speed;
if (e.target.y > 800) {
e.target.y = 800;
}
} else {
e.target.visible = false;
}
}
stop();
I can see that the line...
loveXList.splice(loveXName, 1);
...might be causing problems. Firstly, the first parameter of the Array .splice method should be of type int. You are passing in a String. To remedy that, store the randomly selected index of the loveXList Array in an int variable, use that get your loveXName String and use the int again to splice out the correct String from the loveXList Array, ie:
var randomIndex:int = Math.floor(Math.random() * loveXList.length);
var loveXName: String = loveXList[randomIndex];
...
loveXList.splice(randomIndex, 1);
Secondly, you will quickly run out of Strings to splice out of the loveXList Array so, at the start of the countLoveX function, check if loveXList.length>0. If loveXList.length==0 you may want to stop the timer.

Resources