简体   繁体   English

如何改进我的自定义JavaScript数组反向函数?

[英]How to improve my custom JavaScript Array Reverse Function?

I am looking to improve a function I wrote for array reversal. 我正在寻找改进我为阵列反转写的函数。 I was interested in writing my own just for practice and I came up with this: 我有兴趣为练习写自己的东西,我想出了这个:

function rArray(array){
    var temp = [];
    var len = array.length - 1;
        for(i = len, index = 0 ; i >= 0; i--, index++){
            temp.push(array[i]); // temp[index] = array[i];
        }
    return temp;
}

I am looking to 1.) improve speed, and two, create a more efficient function by leaving less of a footprint, I want to make a destructive reversing function. 我期待1.)提高速度,两个,通过留下更少的足迹创造更有效的功能,我想做一个破坏性的反转功能。 Can this be done with a for loop or must I use a while()? 这可以用for循环完成还是我必须使用while()? Thanks for the input. 感谢您的投入。

You could get rid of index , since you aren't using it. 你可以摆脱index ,因为你没有使用它。

Or you could pre-allocate temp 或者你可以预先分配temp

     var temp = new Array(len);

You can't do both, though, since you would need index to add to the pre-allocated temp . 但是,你不能同时做到这两点,因为你需要index来添加到预先分配的temp You could run some experiments to see at what length pre-allocation becomes preferable (my guess: several million). 您可以运行一些实验来查看预分配的长度变得更合适(我猜:几百万)。

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

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