Define variables u=using for loop - javascript

I am new to javascript, how can I write this using for loop?
SortingPageAudio.prototype.cardAudios = function(cardNumber) {
var page = tabs.page;
var card1Audio = page.card1Audio;
var card2Audio = page.card2Audio;
var FRcard1Audio = card1Audio.replace("e_", "f_");
var FRcard2Audio = card2Audio.replace("e_", "f_");
if(cardNumber == '1')
{
playAudio.playFiles(FRcard1Audio));
}
else if(cardNumber == '2')
{
playAudio.playFiles(FRcard2Audio));
}
};

I don't see any need for a loop, as the function either does card 1 or card 2. If you want the code to be less repetitive, you can do this:
SortingPageAudio.prototype.cardAudios = function(cardNumber) {
var cardAudio = tabs.page["card" + cardNumber + "Audio"];
var FRcardAudio = cardAudio.replace("e_", "f_");
playAudio.playFiles(FRcardAudio);
};
In JavaScript, you can refer to a property either using dot notation and a property name literal (obj.foo), or using brackets notation and a property name string (obj["foo"]). In the latter case, the string can be the result of any expression.
If you wanted to call cardAudios for both cards, you could do it like this:
[1, 2].forEach(instance.cardAudios, instance);
(Where instance is a SortingPageAudio instance.)
Or with a simple for loop:
var card;
for (card = 1; card <= 2; ++card) {
instance.cardAudios(card);
}
Or of course:
instance.cardAudios(1);
instance.cardAudios(2);

Related

Oracle Apex changing a String of a object

So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);

Retrieve value of variables from a string of declarations

I have the following string named abc (which consists of javascript variables declarations):
var abc = `
var exp = 'test';
var test = 15;
var test2 = "wow";
`;
I would like to get the value of exp, test, test2 from this string.
One of the methods that might work is:
eval(abc);
However this solution is not suitable in typescript for security purposes, what other methods would you recommend ( feel free to propose some npm libraries) ?
Creating a function and passing the variable.
new Function has a closed scope in comparison to function eval.
var abc = `
var exp = 'test';
var test = 15;
var test2 = "wow";
`;
var fn = (variable) => (new Function('', `${abc} return ${variable};`))();
console.log(fn('exp'));
console.log(fn('test'));
console.log(fn('test2'));
One way to do that would be the following:
First we find the declarations by splitting the string using ; as delimiter
Now after we have found the declarations we use map() to extract the values of each one and return it into a new array.To find the value of a declaration we split it into 2 parts using '='.The first part is the declaration name and the second part is the declaration value
var abc = `var exp = 'test';
var test = 15;
var test2 = "wow";`;
//Trim string
abc = abc.trim();
//Split by ';'
var declarations = abc.split(';');
//The last item is empty so we remove it
declarations.pop();
console.log(declarations)
//Now that we have the declarations we need to get the values
//so we split each declaration using '='
var values = declarations.map(function(dec){
var value = dec.split("=").pop()
return value;
});
//Bonus
//This gets all declarations from a string and returns them as a key value object
function getDeclarations(s) {
var variables = s.split(";");
//Last variable is an empty string so pop it
variables.pop()
var declarations = {};
variables.forEach(function (variable) {
variable = variable.trim()
var name = variable.split("=")[0].split("var")[1];
var value = variable.split("=").pop();
name = name.trim();
value = value.trim();
declarations[name] = value;
});
return declarations;
}
console.log(values)
console.log(getDeclarations(abc))

re-Naming variables by properties (JavaScript)

In a JavaScript code, I am trying to re-name an object by its stored data. I tried using pathTo as suggested by this site (http://thedesignspace.net/MT2archives/000381.html), but my console returns "ReferenceError: 'pathTo' is undefined". My code looks something like this:
// This code defines the Object constructor Card, used to make the card objects
var Card = function() {
this.face = theFace(this);
this.suit = theSuit(this);
this.value = theValue(this);
};
// This code creates the Deck to be used.
var deck = [];
for ( i=0 ; i<52 ; i++ ) {
deck.push( i );
};
for ( i=51 ; i>0 ; i-- ) {
var random = Math.floor(Math.random()*i);
var temp = deck[random];
deck[random] = deck[i];
deck[i] = temp;
};
// 0-12 is Spades.
// 13-25 is Hearts.
// 26-38 is Clubs.
// 39-51 is Diamonds.
// Now we create the hand of the player and dealer
var player = [];
var dealer = [];
// Now to deal a card to player
player.push(deck.pop());
dealer.push(deck.pop());
// and another
player.push(deck.pop());
dealer.push(deck.pop());
// function theFace gives the face of a card
function theFace( card ) {
var faces = ["King","Ace","2","3","4","5","6","7","8","9","10","Queen","Jack"];
return(faces[card%13]);
};
// function theValue uses 'switch' to determine points from a card
function theValue(card) {
var value = card % 13;
switch( value ) {
case(0):
case(11):
case(12):
value = 10;
break;
case(1):
value = 11;
break;
default:
value = value;
break;
};
return value;
};
// function theSuit returns the suit of a card
function theSuit(card) {
var suit;
if(card>38) {
suit = "Diamonds";
}else if(card>25) {
suit = "Clubs";
}else if(card>12) {
suit = "Hearts";
}else {
suit = "Spades";
};
return suit;
};
// function toObject the first (numbered) card of of a hand
// and turns it into an Object with the desired properties
function toObject( hand ) {
var card = hand.shift();
if (typeof(card) !== "number") {
hand.unshift(card);
} else {
var card = new Card ();
card = pathTo[card.suit + card.face];
};
return hand;
};
console.log(player);
toObject(player);
toObject(player);
console.log(player);
I am trying to rename the card I am turning from a typeof==="number" to typeof==="object" so that when I run the code multiple times (hence the function) I do not have duplicate names of the objects in the array of hands.
Here are some examples of what my console is printing:
[ 19, 46 ]
ReferenceError: 'pathTo' is undefined
and
[ 31, 18 ]
ReferenceError: 'pathTo' is undefined
There MUST be a way to do this, I just cannot find how.
In function toObject I am trying to take the first number(card) in the hand array and turn it into an object describing its qualifiers as a card of the standard 52 card deck. EDIT: I just realized I'm not even pushing it back. I am going to try something to see if it will work.
EDITEDITEDIT_SOLVED:
I have done it! It turns out that I don't need to change the name, the code will keep it separate for me somehow. All I needed to do so that it runs correctly is this:
Replace
var Card = function() {
this.face = theFace(this);
this.suit = theSuit(this);
this.value = theValue(this);
};
with
var Card = function(card) {
this.face = theFace(card);
this.suit = theSuit(card);
this.value = theValue(card);
};
and
function toObject( hand ) {
var card = hand.shift();
if (typeof(card) !== "number") {
hand.unshift(card);
} else {
var card = new Card ();
card = pathTo[card.suit + card.face];
};
return hand;
};
with
function toObject( hand ) {
var card = hand.shift();
if (typeof(card) !== "number") {
hand.unshift(card);
} else {
var card = new Card (card);
hand.push(card);
};
return hand;
};
Thanks for the help!
As #mattbornski points out, there is no pathTo object in JavaScript and, as far as I know, it's not supported by any browser anywhere. That article seems to have omitted this part of their code.
Based on how you're trying to use it, though, you'll want to make a few changes to your code:
Create a pathTo object like this:
pathTo = {};
or
pathTo = new Object();
Then, give each new Card object a suit and face before you try to add it to pathTo (or before you try to use it to look up a card). For example, you could write:
myCard = new Card(23);
or
myCard = new Card('spade','2');
Finally, when your card has both a face and a suit, add it to the pathTo object like this:
pathTo[this.suit + this.face] = this; // use this inside the Card constructor
or
pathTo[myCard.suit + myCard.face] = myCard; // use this with an instance of a Card object
Then you can look up the cards with:
pathTo['spade2']
The website you are reading from is documenting array syntax. It is not documenting a function called pathTo - there is no such built in function, so referring to it will cause a ReferenceError.
Perhaps you should define an object and refer to that instead.

javascript parsing variable names/values from a form

I am having trouble running this code, any one has idea what could be wrong with it?
please check line # 4
for(i=0; i<document.anyForm.elements.length; i++) {
element_type = document.anyForm.elements[i].type;
if(element_type.toUpperCase() == "TEXT" || element_type.toUpperCase() == "TEXTAREA") {
var parse(document.anyForm.elements[i].name) = document.anyForm.elements[i].value;
}
}
var parse(document.anyForm.elements[i].name)
This is incorrect. you either need to define a variable or invoke a function var before the function invocation is invalid.
EDIT:
you can use an object to store the name:value pairs:
var obj = {}; // before loop
//in loop
obj[document.anyForm.elements[i].name] = document.anyForm.elements[i].value;

javascript function arguments

i want to pass an array to a function and work on it,but i am afraid ,error occurs saying board_pt is undefined. What is the problem? This is the code :
function set_boardPoint( board_pt,turn)
{
var no = board_pt.number-1;
board[no].row = board_pt.row;
board[no].col = board_pt.col;
board[no].x = board_pt.x;
board[no].y = board_pt.y;
board[no].value = turn;
board[no].number = board_pt.number;
}
board is a global array already defined
The problem is that board_pt have only 1 item, and js in these case know board_pt as object:
function set_boardPoint( board_pt,turn)
{
var no = board_pt.number-1;
if( board[no] != undefined )
{
board[no].row = board_pt.row;
board[no].col = board_pt.col;
board[no].x = board_pt.x;
board[no].y = board_pt.y;
board[no].value = turn;
board[no].number = board_pt.number;
}else
{
board.row = board_pt.row;
board.col = board_pt.col;
board.x = board_pt.x;
board.y = board_pt.y;
board.value = turn;
board.number = board_pt.number;
}
}
If board_pt is a real array, then it's unlikely that it has a property named number. Do you mean length?
From your comments, you have to define the previous_boardPoint as an array. To declare a array in javascript, you need to have - var previous_boardPoint = []; in your code. Also have each elements defined (if you have any) like previous_boardPoint[0] = val1; previous_boarPoint[1] = val2; etc.
If these things are not in your code, then in all likely possibilities, you will get board_pt as undefined in your function set_boardPoint.

Categories