gpt4 book ai didi

Javascript 的数组反转

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:15 27 4
gpt4 key购买 nike

Javascript 的 array.reverse() 究竟是如何工作的?它是否遍历并交换数组的每个元素?如果是这样,是否需要 O(n) 来交换大小为 n 的数组?

我想我问的原因是因为我想知道 array.reverse() 是否与以下内容相同:

for(var i = 0; i < a.length / 2; i++) {
var holder = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = holder;
}

注意:抱歉,如果我发布的 Javascript 代码不正确,现在已经很晚了。

编辑:将a.length 固定为a.length/2

最佳答案

有关其工作原理的完整详细信息,read the relevant section of the spec .这是算法:

  1. Let O be the result of calling ToObject passing the this value as the argument.

    1. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length".
    2. Let len be ToUint32(lenVal).
    3. Let middle be floor(len/2).
    4. Letlower be 0.
    5. Repeat, while lower ≠ middle

      1. Let upper be len−lower −1.
      2. Let upperP be ToString(upper).
      3. Let lowerP be ToString(lower).
      4. Let lowerValue be the result of calling the [[Get]] internal method of O with argument lowerP.
      5. Let upperValue be the result of calling the [[Get]] internal method of O with argument upperP .
      6. Let lowerExists be the result of calling the [[HasProperty]] internal method of O with argument lowerP.
      7. Let upperExists be the result of calling the [[HasProperty]] internal method of O with argument upperP.
      8. If lowerExists is true and upperExists is true, then

      9. Call the [[Put]] internal method of O with arguments lowerP, upperValue, and true .

      10. Call the [[Put]] internal method of O with arguments upperP, lowerValue, and true .
      11. Else if lowerExists is false and upperExists is true, then
      12. Call the [[Put]] internal method of O with arguments lowerP, upperValue, and true .
      13. Call the [[Delete]] internal method of O, with arguments upperP and true.
      14. Else if lowerExists is true and upperExists is false, then
      15. Call the [[Delete]] internal method of O, with arguments lowerP and true .
      16. Call the [[Put]] internal method of O with arguments upperP, lowerValue, and true .
      17. Else, both lowerExists and upperExists are false
      18. No action is required.
      19. Increase lower by 1.
    6. Return O .

关于Javascript 的数组反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7912677/

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