繁体   English   中英

为什么 splice 会删除我的整个数组? 如果 max 在位置 0,我只想删除它

[英]Why is splice deleting my entire array? I would only like to delete max if it is in position 0

我正在使用以下说明处理 leet 代码问题:

给定一个数组价格,其中价格 [i] 是给定股票在第 i 天的价格。

您希望通过选择一天购买一只股票并选择未来的另一天出售该股票来最大化您的利润。

返回您可以从此交易中获得的最大利润。 如果您无法获得任何利润,则返回 0。

在下面的代码中,我希望仅当它位于数组的索引 0 中时才从数组中删除 Max 数。 检查调试器时,我看到除索引 0 之外的整个数组都被删除了。为什么 splice 没有按预期工作?

调试器显示什么leetcode 调试器视图显示整个数组已删除

var maxProfit = function (prices) {
  let theMin = Math.min(...prices)
  let minPosition = prices.indexOf(theMin)
  let theMax = Math.max(...prices)
  let maxPosition = prices.lastIndexOf(theMax)

  if (maxPosition === 0) {
    prices = prices.splice(0, 1)
    if (prices.length === 0) {
      return 0
    }

    maxProfit(prices)
  }

  return theMax - theMin
};

splice不返回数组的修改副本。 数组被就地修改,返回的是被删除的子数组(如果有的话)。

实际上,您的代码是:

const deletedElements = prices.splice(0, 1);
prices = deletedElements;

您从数组中删除了第一个元素,然后将该数组替换为另一个仅包含第一个元素的数组。 因此,正如您所声称的那样,并不是只返回第一个元素。 splice的工作方式与文档完全一致。


此外, prices.splice(0, 1)更清晰地写为prices.shift()

暂无
暂无

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

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