Javascript变量:调用函数对变量内的数组进行排序,如何使变量的数组更改为原始排序?
好朋友们! 我只是想问,如果通过调用函数数组已经被更改了好几次,如何检索变量中数组的原始内容 这是密码Javascript变量:调用函数对变量内的数组进行排序,如何使变量的数组更改为原始排序?,javascript,arrays,sorting,Javascript,Arrays,Sorting,好朋友们! 我只是想问,如果通过调用函数数组已经被更改了好几次,如何检索变量中数组的原始内容 这是密码 $(document).ready(function() { var cars = ['Honda', 'Mazda', 'Toyota', 'Ambulance']; // store cars in my cars variable document.getElementById('param').innerHTML = cars; // display
$(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);
});
所以我的问题是,我的cars变量中的原始内容在哪里?如果可能的话,如何检索它?谢谢因为
排序
函数将数组排序到位(意味着原始数组被更改),所以您需要做一些不同的事情。例如,在对数组排序之前复制它。
几种解决方案:
cars.slice().sort();
或
希望这有帮助
$(文档).ready(函数(){
var cars=[‘本田’、‘马自达’、‘丰田’、‘救护车’];//将汽车存储在我的汽车变量中
document.getElementById('param').innerHTML=cars;//在我的html中显示汽车
函数sortCars(){
var数组=cars.slice();
array.sort();//sort
document.getElementById('param').innerHTML=array;
}
函数unsortCars(){
document.getElementById('param').innerHTML=cars;
}
$('#sort')。在('click',sortCars');
$('#unsort')。在('click',unsortCars');
});代码>
排序
unsort
您可以在JSFIDLE中或内部重新创建吗?
cars.concat().sort();