0

I am trying to push the following element to an object that contains three properties. I would like one of the properties being pushed to reference a separate property that is being pushed with it.

I would like to turn this code (property "y"):

if (oncoming[i].x == 600) {
            oncoming.push({
                pokemon : Math.random() < 0.70 ? kabutops : aerodactyl,
                x       : cvs.width,
                y       : runningHeight
            });
        }

Into something resembling this (again, with respect to property "y"):

if (oncoming[i].x == 600) {
            oncoming.push({
                pokemon : Math.random() < 0.70 ? kabutops : aerodactyl,
                x       : cvs.width,
                y       : this.pokemon == aerodactyl ? flyingHeight : runningHeight
            });
        }

The W3 docs (https://www.w3schools.com/js/js_this.asp) tell me that, when used in a method, the "this" keyword refers to the owner object. In this example, the owner object, oncoming[i], has a y value of runningHeight. So I don't think I can use "this" in this instance.

Is there another approach I should be taking to this? Am I incorrect in thinking that "this" is not appropriate here? Thanks for your help.

mikekoscinski
  • 555
  • 1
  • 4
  • 14
  • why not just declare pokemon outside of push than use the ternary operator on that value? – jmkmay Jun 18 '20 at 19:35
  • Yes, that worked - thank you. For context, this is within a draw() function for a side-scrolling game. I initialize "oncoming" and then add oncoming[0]. The draw function I wrote adds all other elements to "oncoming", randomly generating them – mikekoscinski Jun 18 '20 at 19:47

1 Answers1

0
if (oncoming[i].x == 600) {
            let newPokemon = Math.random() < 0.70 ? kabutops : aerodactyl
            oncoming.push({
                pokemon : newPokemon,
                x       : cvs.width,
                y       : newPokemon == aerodactyl ? flyingHeight : runningHeight
            });
        }
jmkmay
  • 1,441
  • 11
  • 21