gpt4 book ai didi

arrays - 意外的数组大小

转载 作者:行者123 更新时间:2023-12-03 00:42:13 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Powershell Join-Path showing 2 dirs in result instead of 1 - accidental script/function output

(1 个回答)


2年前关闭。




我正在尝试制作一个简单的二十一点游戏作为 Powershell 脚本,发现我的 ArrayList未按预期运行。我想了解为什么我得到的答案与预期的不同。
Write-Host $deck函数内部的调用按我的预期打印出甲板,52 个对象。到现在为止还挺好。

但是,当调用 Write-Host $myDeck奇怪的部分开始了。它会做的是,它会首先打印 0...51,然后是我的实际套牌。所以我的 ArrayList 中没有 52 个对象我得到 104 (52+52)。谁能解释这里到底发生了什么?因为我觉得这 super 困惑。

function Get-Deck(){

$ranks = 2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"
$suits = "Spade","Heart","Diamond","Club"
$deck = [System.Collections.ArrayList]::new()

foreach($rank in $ranks){
foreach($suit in $suits){
$card = $rank , $suit
$deck.Add($card)
}
}

Write-Host $deck #prints out the actual array with 52 cards.
return $deck

}

$myDeck = Get-Deck
Write-Host $myDeck #prints out: 0 1 2 3 4 5 6 7 ... 51 2 Spade 2 Heart 2 Diamond ... Ace Club

最佳答案

意外的输出是由 ArrayList.Add() 引起的.函数原型(prototype)是这样的,

public virtual int Add (object value);

请注意,它有一个非 void 返回类型 int这是添加值的 ArrayList 索引。

$deck.Add($card)被调用时,返回值留在管道上并最终在 arraylist 中。要解决此问题,请将返回值分配给显式变量,传递给 null 或强制转换为 void。有一些陷阱,请参阅 another an answer关于那些。这些中的任何一个都应该起作用。像这样,
$null = $deck.Add($card) # Preferred, (ab)uses automatic variable
[void]$deck.Add($card) # Works too
$deck.Add($card) | out-null # Works, but is the slowest option
$foo = $deck.Add($card) # Use this if you need the index value

关于arrays - 意外的数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58604984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com