0

In the p5 javascript library, there's a built-in function {key} which is the key you press. For example text(${key},200,200) would display whatever key your pressing on 200,200. If I were to push the {key} value into an array so the array has the key value you pressed, then console.log() the value from the array, you'd get: Object {key: "a}. If you were to put this into a text, say you press "A" then you push A into the array. Then you put that into text (Granted A is the only value in the array) text(Array_Of_Text[0],Xposition,Yposition); The text is simply "Object, Object" So I'd assume I'd have to find the value from the object, which I don't know how to do.

let Text = [];

function setup() {
  createCanvas(400, 400);
}

function draw() {
background(220);
text(Text[0],200,200);
console.log(Text[0])

}
function keyPressed()
{
  Text.push({key})
}
user15302406
  • 132
  • 9

2 Answers2

3

You don't need the curly brackets around key, you can just say Text.push(key).

The built-in function is simply key, not {key}. When you put brackets around it, it becomes an object according to ES6 syntax. So if key === "a", writing {key} is the same as writing {key: "a"}:

let key = "a";
console.log({ key });
console.log({ key: "a" });

The above code will print "Object {key: "a"}" twice. You can't test this using == or === because JavaScript doesn't work like that.

The same goes for any other variable or data type: if valu === 200, then {valu} is the same as {valu: 200}:

let valu = 200;
console.log({ valu });
console.log({ valu: 200 });
//prints "Object {valu: 200}" twice
Jacob Stuligross
  • 1,434
  • 5
  • 18
  • Thank you for the simple answer, could you please elaborate on why this works this way. (Sorry for the extremely late reply) – user15302406 Jun 28 '21 at 17:00
1

You can just nest things in javascript. I think you can even refer to objects like: Text[0][0]. Since you can totally have a: let string = "hello"; console.log(string[0])
> "h"

if(Text[0].key !== undefined){
    console.log(Text[0].key)
}

(And this has already been answered, i think)

Ulti
  • 514
  • 3
  • 5