Change object property depending on integer value in javascript [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 7 years ago.
I have an object, Player, which has different properties for different rounds for example round_1, round_2, .. , round_7. I would like to give them values depending on the integer, round value.
What i thought would work would be with a function:
//voor = round in Estonian
function valiVoor(player, r){
if (r == 1){
return player.voor_1;
}
else if (r == 2){
return player.voor_2;
}
else if (r == 3){
return player.voor_3;
}
else if (r == 4){
return player.voor_4;
}
else if (r == 5){
return player.voor_5;
}
else if (r == 6){
return player.voor_6;
}
else if (r == 7){
return player.voor_7;
}
}
Although calling out function:
valiVoor(player_one,1) = "asd";
Will not change the property player_one.voor_1 = "asd". Should i work with arrays or is there any other option to resolve the issue?

You could use the Bracket notation:
player['voor_' + r] = 'asd'; //Equivalent to player.voor_# where # is the number r
If you want to check if the property exists before assigning (otherwise if r goes crazy it takes your player object in its madness):
if(player.hasOwnProperty('voor_' + r)) {
//Do stuff
}
See this MDN link for Object.prototype.hasOwnProperty.

function valiVoor(player, r){
return player['voor_'+r];
}
And a setter:
function setValiVoor(player, r, value){
player['voor_'+r] = value;
}

You can also access Object properties with the squared brackets just like Arrays.
function getValiVoor(player, r){
return player['voor_' + r];
}
If you want to assign a value, you could pass the value to the function:
function setValiVoor(player, r, val){
player['voor_' + r] = val;
}

Related

How does instanceof operator actually work in JS? [duplicate]

This question already has answers here:
Why is 4 not an instance of Number?
(5 answers)
Closed 8 months ago.
I've searched the site for this question and got the following answer:
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
It's from https://stackoverflow.com/a/9220317/12974414.
But I tested the following code, found something weird:
console.log( (10).__proto__ === Number.prototype ) // true
console.log( instance_of(10, Number ) ) // true
console.log( 10 instanceof Number ) // false
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
How to explain this and how does instanceof operator actually work in JS ?
JavaScript has a feature called autoboxing which converts primitives to Objects when you try to access properties on them.
instanceof doesn't autobox and a primitive number is not an instance of the Number class.
You can see, in the specification:
If Type(O) is not Object, return false.

What happens when you return a value with or "||" operator? [duplicate]

This question already has answers here:
How does this recursion work?
(11 answers)
Closed 2 years ago.
I'm not trying to get or want anything from this code. I just have a confusion with a part of the following code. The author has returned a value with or || operator. my question is which value will be returned and when?
function findSolution (target) {
function find (current, history) {
if (current == target) {
return history
}else if (current > target) {
return null
} else {
return find (current + 5, `${history} + 5)`) ||
find(current * 3, `(${history} * 3)`)
}
}
return find(1, '1')
}
console.log(findSolution(24))
here is the part of the code is bothering me
return find (current + 5, `${history} + 5)`) ||
find(current * 3, `(${history} * 3)`)
can anyone please tell me, which value when return? and why?
From MDN:
If expr1 can be converted to true, returns expr1; else, returns expr2.
in other words, you can see it as a function like this:
const or = (fel, sel) =>{
if(fel) return fel;
return sel;
}
That's why this happens:
const x = 0 || 1; // x == 1
// same as:
//
// const or = (fel, sel) =>{
// if(fel) return fel;
// return sel;
// }
// const x = or(0,1)

Javascript program yields undefined (recursion) [duplicate]

This question already has answers here:
Simple Recursive Javascript Function Returns Undefined
(2 answers)
Closed 4 years ago.
Hello I am a newbie learning Js
I am trying to learn about recursion but I stuck in here
var isEven = (number) =>{
number = Number(number)
if(number === 0){
console.log('it is even')
return true;
}
else if(number === 1){
return false;
}
else{
number = number - 2;
isEven(number);
}
}
console.log(isEven(50) === true)
why the end result becomes undefined? Thank you for the help
Add return in recursion call:
function isEven(number){
number = Number(number)
if(number === 0){
console.log('it is even');
return true;
}
else if(number === 1){
return false;
}
else{
number = number - 2;
return isEven(number);
}
}
console.log(isEven(50));
You must use return in recursion call .If u do not use return the isEven(50) function will run but do not return isEven(48) so your function isEven(50) get undefined.So always use return.
Example
function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}
In above example you can when we call factorial(n-1); it will return (n-1)*factorial(n-2); but if u remove the return then result is undefined as factorial(n-1); do not return anything.
Always remember in recursion focus is on returning function again and again till we get the result.

why recursion is returning undefined in javascript? [duplicate]

This question already has answers here:
Recursive function returns undefined
(3 answers)
Closed 4 years ago.
I'm using recursion to reverse the number. in the terminating condition i am returning the result. but it's returning "undefined". the console inside the if is showing the correct output.
// reverse the number
var result= "";
var reverse = function(x) {
if(x == 0){
console.log("result",result);
return result;
}else{
var lastDigit = x % 10;
result += lastDigit;
x = Math.floor(x/10);
reverse(x);
}
};
console.log(reverse(73254));
That's because you're not returning a call to function itself and by default undefined is returned.
The solution is to return the result from reverse(x).
Also, you can simplify your function like this:
var reverse = function(x) {
if(x < 10)
return x;
return x % 10 + "" + reverse(Math.floor(x/10));
};
console.log(reverse(73254));
If you do not return anything from function with return then by default undefined is returned. You have to return the function from else like:
return reverse(x);
Working Code Example:
var result= "";
var reverse = function(x) {
if(x == 0){
console.log("result",result);
return result;
}else{
var lastDigit = x % 10;
result += lastDigit;
x = Math.floor(x/10);
return reverse(x);
}
};
console.log(reverse(73254));

Chained logical OR comparison [duplicate]

This question already has answers here:
Javascript if statement with multiple permissible conditions [duplicate]
(4 answers)
Closed 5 years ago.
Why doesn't this work:
if (x != (a || b || c)) {
doStuff();
}
It's meant to check whether x is NOT equal to a OR b OR c.
EDIT: How would I achieve a check for whether x is NOT equal to a OR b OR c?
EDIT: Ok, it's a duplicate. What do I do now, take minus points even after realizing my mistake? :P
To use multiples values like you wanna just:
var x = 'x';
var a = 'a';
var b = 'b';
var c = 'c';
function doStuff() {
console.log(1)
}
// exemple 1
if(x == a || x == b || x == c) {
doStuff();
}
function isSameValue(element, index, array) {
return element === x;
}
// exemple 2
if([a, b, c].some(isSameValue)) {
doStuff();
}
// exemple 3
[a, b, c].includes(x);

Categories