[英]Why is splice deleting my entire array? I would only like to delete max if it is in position 0
I'm working on a leet code problem with the following instructions:我正在使用以下说明处理 leet 代码问题:
You are given an array prices where prices[i] is the price of a given stock on the ith day.给定一个数组价格,其中价格 [i] 是给定股票在第 i 天的价格。
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.您希望通过选择一天购买一只股票并选择未来的另一天出售该股票来最大化您的利润。
Return the maximum profit you can achieve from this transaction.返回您可以从此交易中获得的最大利润。 If you cannot achieve any profit, return 0.如果您无法获得任何利润,则返回 0。
In my code below, I expect to remove the Max number from the array only if it's in index 0 of the array.在下面的代码中,我希望仅当它位于数组的索引 0 中时才从数组中删除 Max 数。 When checking the debugger, I see that the entire array is deleted except index 0. Why is splice not working as intended?检查调试器时,我看到除索引 0 之外的整个数组都被删除了。为什么 splice 没有按预期工作?
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
does not return a modified copy of the array. splice
不返回数组的修改副本。 The array is modified in-place, and what is returned is the deleted subarray, if any.数组被就地修改,返回的是被删除的子数组(如果有的话)。
In effect, your code is:实际上,您的代码是:
const deletedElements = prices.splice(0, 1);
prices = deletedElements;
You deleted the first element from the array, then replaced that array with another array which only contains the first element.您从数组中删除了第一个元素,然后将该数组替换为另一个仅包含第一个元素的数组。 Thus, it is not that only the first element is returned, as you claim.因此,正如您所声称的那样,并不是只返回第一个元素。 splice
is working exactly as documented. splice
的工作方式与文档完全一致。
Also, prices.splice(0, 1)
is more legibly written as prices.shift()
.此外, prices.splice(0, 1)
更清晰地写为prices.shift()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.