简体   繁体   English

传递一个返回数组作为参数的函数

[英]Passing a function which returns array as a parameter

I have two functions:我有两个功能:

function drawCard(player) {

let imageCard = document.createElement('img');
let imageId = getRandomCard();
player['cards'].push(imageId);
imageCard.src = "static/image/PNG/"+ imageId + ".png";
return [imageCard, imageId];}

and

function showCard(card, id, player) {
document.querySelector(player['div']).appendChild(card);
upgradeScore(id,player);}

I am trying to pass values imageCard and imageId returned from function drawCard() by calling a function drawCard() in showCard() arguments but I can't find the way to do so.我试图通过在showCard()参数中调用函数drawCard()来传递从函数drawCard()返回的值imageCardimageId ,但我找不到这样做的方法。 Is there a nice and tidy way to do it?有没有一种既漂亮又整洁的方法呢?

Yes,是的,

You can use array destructuring to pass in the return values of drawCard as arguments for showCard .您可以使用数组解构将drawCard的返回值作为drawCard参数showCard

let player =  [...]
// ^ Assuming that you have declared the player variable elsewhere

showCard(...drawCard(player), player)
// The two values returned by the drawCard function are taken out of the array and passed in as arguments

// Equivalent to showCard(drawCard(player[0]), drawCard(player[1), player)

More on destructuring assignment 更多关于解构赋值

It looks like everything is dependent on your player variable.看起来一切都取决于您的玩家变量。

You can use it as the only argument and then call the drawCard method.您可以将其用作唯一参数,然后调用 drawCard 方法。 Destructure the returned array into two variables and then use them as you wish.将返回的数组分解为两个变量,然后根据需要使用它们。

function showCard(player) {
let [card,id] = drawCard(player);
document.querySelector(player['div']).appendChild(card);
upgradeScore(id,player);}

hope this help cause your demande is a kind of not clear.希望这有助于导致您的需求者不清楚。

function drawCard(player) {
    let imageCard = document.createElement('img');
    let imageId = getRandomCard();
    player['cards'].push(imageId);
    imageCard.src = "static/image/PNG/"+ imageId + ".png";
    return [imageCard, imageId];
}

function showCard(card, id, player) {
    let imageCardAndImageId = drawCard(player);
    document.querySelector(player['div']).appendChild(imageCardAndImageId[0]);
    upgradeScore(imageCardAndImageId[1],player);
}

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

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