索引-1越界,数组大小为0

Index -1 is out of bounds, array size is 0

目标是快速识别性能最差的路径和性能最差的损失。我遇到的挑战是,在我用 var 初始化变量后,array.get() 函数不再能够检索数组内的值。我收到的只是错误消息 Index -1 is out of bounds, array size is 0。在下面的示例中,我能够成功创建两个数组,一个包含所有损失路径名称,另一个包含所有损失百分比。在理想情况下,我想在右上角的第一个 table 单元格中绘制性能最差的路径名,这对应于第二个 table 单元格中性能最差的损失(工作) .有什么建议吗?

var lossPath = array.new_string(0)
var lossPercent = array.new_float(0)
if (change(entryPrice) and color_WINLOSS == color.new(color.red, 0))
    array.push(lossPath, path[1])
    percent = isLong ? (entryPrice[0] - entryPrice[1]) / entryPrice[1] * 100 : isShort ? -(entryPrice[0] - entryPrice[1]) / entryPrice[1] * 100 : na
    array.push(lossPercent, percent)
if barstate.islast
    label.new(bar_index, high, "Loss Path: " + tostring(lossPath) + "\nLoss Percent: " + tostring(lossPercent) + "\nArray Size: " + tostring(array.size(lossPath)), style=label.style_label_down)

worstPathIndex = array.indexof(lossPercent, array.min(lossPercent))
worstPathName = tostring(array.get(lossPath, min(worstPathIndex, array.size(lossPath) - 1)))
// plot(array.get(lossPercent, 0)) // Similarity this plot doesn't work either
worstLoss = tostring(array.min(lossPercent), format.percent)

它正在发生,因为在这条线上:

worstPathName := tostring(array.get(lossPath, min(worstPathIndex, array.size(lossPath) - 1)))

在第一个柱上,lossPath 数组为空,包含零个元素。因此 array.size 将 return 归零,导致 array.get 尝试访问索引“0 减 1”。

如果在此之前先检查判断数组是否为空,则可以避免错误。

string worstPathName = na
if array.size(lossPath) > 0
    worstPathName := tostring(array.get(lossPath, min(worstPathIndex, array.size(lossPath) - 1)))