Javascript变量:调用一个函数来对变量内部的数组进行排序,如何使变量数组更改为原始排序?

时间:2016-12-20 06:46:44

标签: javascript arrays sorting

美好的一天伴侣! 我只是想问一下如果通过调用函数已经多次改变,我怎样才能检索变量中数组的原始内容?

继承人的代码

$(document).ready(function() {

        var cars = ['Honda', 'Mazda', 'Toyota', 'Ambulance']; // store cars in my cars variable

        document.getElementById('param').innerHTML = cars; // display the cars in my html

        function sortCars() {
            cars.sort(); // sort the cars
            document.getElementById('param').innerHTML = cars; display sorted cars
            $('#btn').css('opacity', '0');
            $('#unsort').css(
                'opacity', '1'
                );
        }

        function unsortCars() {
            document.getElementById('param').innerHTML = cars; //what i expect to happen here is that the content of the cars which is first declare is the same. but it seems the cars variable original value is sorted already
            $('#btn').css('opacity', '1');
            $('#unsort').css('opacity', '0');
        }

        $('#sort').on('click', sortCars);
        $('#unsort').on('click', unsortCars);

    });

所以我的问题是我的汽车变量中的原始内容在哪里以及如果可行的话如何检索它?感谢

2 个答案:

答案 0 :(得分:1)

由于sort函数对数组进行了排序(意味着原始数组发生了变化),因此您需要采取不同的方式。例如,在对数组进行排序之前复制该数组。 几点解决方案:

cars.slice().sort();

或者

cars.concat().sort();

希望这有帮助

答案 1 :(得分:0)



$(document).ready(function() {

        var cars = ['Honda', 'Mazda', 'Toyota', 'Ambulance']; // store cars in my cars variable

        document.getElementById('param').innerHTML = cars; // display the cars in my html

        function sortCars() {
            var array = cars.slice();
            array.sort(); // sort 
            document.getElementById('param').innerHTML = array;
        }

        function unsortCars() {
            document.getElementById('param').innerHTML = cars; 
        }

        $('#sort').on('click', sortCars);
        $('#unsort').on('click', unsortCars);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="param"></p>
<p id="sort">sort</p>
<p id="unsort">unsort</p>
&#13;
&#13;
&#13;