简体   繁体   English

如何在 javascript 中调用具有多个值的 function? 移相器3

[英]how do I call a function with multiple values in javascript? phaser3

I'm a javascript beginner and I know I should read the tutorials and all.我是 javascript 初学者,我知道我应该阅读教程和所有内容。 However the tutorials only mention how to return a value within a function and I want to return multiple values.然而,教程只提到如何在 function 中返回一个值,我想返回多个值。 I'm using phaser 3 and I want to call a function that will give a coin physics.我正在使用移相器 3,我想调用一个 function 来提供硬币物理学。 here's the code这是代码

 function coins(coin) { coin.setBounce(1); coin.body.setGravityY(300); this.physics.add.collider(coin, platforms); this.physics.add.collider(player, coin, collectCoin, null, this); coin.setVelocityX(60); coin.setVelocityY(-300); coin.setCollideWorldBounds(true); }

Please help me out, I've asked a couple of other places and have received no answers.请帮帮我,我已经问了其他几个地方,但没有收到任何答案。

You can not return multiple values in js, but you can return an array or object with all values you need.您不能在 js 中返回多个值,但您可以返回一个数组或 object 以及您需要的所有值。 Like:喜欢:

return [val1, val2]   or   return {val1, val2}

And then access them:然后访问它们:

answer[0]   or   answer.val1   or   answer["val1"]

I've created a simple snippet here for you to a) show how to call a function with multiple arguments;我在这里为您创建了一个简单的片段 a) 显示如何使用多个 arguments 调用 function; and b) how return multiple values from a functino: b) 如何从函数返回多个值:

 class Coin { setBounce(value) {} setVelocityX(value) {} setVelocityY(value) {} setCollideWorldBounds(value) {} body = { setGravityY(value) {}, }; } var physics = { add: { collider(...args) {}, }, }; function coins(coin, platforms, player, collectCoin) { coin.setBounce(1); coin.body.setGravityY(300); this.physics.add.collider(coin, platforms); this.physics.add.collider(player, coin, collectCoin, null, this); coin.setVelocityX(60); coin.setVelocityY(-300); coin.setCollideWorldBounds(true); /* Below is how you return multiple values from a function in this case it's an array of values, but it could be an object too. */ return ["Hello", "World"]; // <- this } let coin = new Coin(); // Below is how you call the function coins with multiple arguments let result = coins(coin, "platforms", "player", "collectCoin"); console.log(result);

Let me know if you have any questions regarding the snippet above.如果您对上面的片段有任何疑问,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM