我尝试反转数组,但没有reverse
函数。
就像您看到我尝试减小数组num=(tab.length-i)-1
的长度一样,所以它可以工作。但是,当我尝试添加tab[i]=tab[num]
时,它可以工作,但tab[i]
内部的值推送是随机的[ 10, 9, 8, 7, 6, 6, 7, 8, 9, 10 ]
。
你知道为什么吗?
const tab=[1,2,3,4,5,6,7,8,9,10]
let num=0
for(let i=0;i<tab.length;i++){
num=(tab.length-i)-1
console.log(num)
tab[i]=tab[num]
}
问题是,您在查看数组的同时正在修改数组,所以当您到达中间元素时,它已经被修改了。
这是脚本的手动执行:
i | tab
0 | [1,2,3,4,5,6,7,8,9,10]
1 | [10,2,3,4,5,6,7,8,9,10]
2 | [10,9,3,4,5,6,7,8,9,10]
3 | [10,9,8,4,5,6,7,8,9,10]
4 | [10,9,8,7,5,6,7,8,9,10]
5 | [10,9,8,7,6,6,7,8,9,10]
6 | [10,9,8,7,6,6,7,8,9,10]
7 | ...
8 | ...
9 | ...
我认为您可以在那里看到问题
有两种方法可以解决此问题:
// either create a temp array to keep previous values
const reverseWithTmpArray = arr => {
let tmp = [...arr]
for(let i = 0; i < arr.length; i++){
let num = (arr.length - i) - 1
arr[i] = tmp[num]
}
return arr
}
// or reverse the element by pairs
const reverseByPairs = arr => {
for(let i = 0; i < arr.length / 2; i++){
let num = (arr.length - i) - 1
let tmp = arr[i]
arr[i] = arr[num]
arr[num] = tmp
// can also be written
// [arr[i], arr[num]] = [arr[num], arr[i]]
// using destructuring assignement
}
return arr
}
console.log(reverseWithTmpArray([1,2,3,4,5,6,7,8,9,10]))
console.log(reverseByPairs([1,2,3,4,5,6,7,8,9,10]))
当我写这两个函数时,它们使输入数组发生变化,可以重写它以防止出现这种副作用
您必须使用一个临时变量。没有这些,您只会覆盖这样的值。
doc of destructuring assignement
改为这样做:
Step 01: 1,2,3,4,5,6,7,8,9,10
Step 02: 10,2,3,4,5,6,7,8,9,10
Step 03: 10,9,3,4,5,6,7,8,9,10
Step 04: 10,9,8,4,5,6,7,8,9,10
Step 05: 10,9,8,7,5,6,7,8,9,10
Step 06: 10,9,8,7,6,6,7,8,9,10
// Now it will just take the values, but they are the same, so you are left with a mirrored array.
Step 07: 10,9,8,7,6,6,7,8,9,10
Step 08: 10,9,8,7,6,6,7,8,9,10
Step 09: 10,9,8,7,6,6,7,8,9,10
Step 10: 10,9,8,7,6,6,7,8,9,10
您可以使用下面的代码片段来反转不具有反向功能的数组
let tab = [1,2,3,4,5,6,7,8,9,10],
temp = []; // Create temp
let num=0
for(let i=0;i<tab.length;i++){
num=(tab.length-i)-1
temp[i]=tab[num] // Add to temp
}
tab = temp; // Assign temp to tab
console.log(tab)
var array = [1,2,3,4,5,6,7,8,9,10];
function reverseIt(array2) {
var newArray = [];
var total = array2.length;
for(var i=0; i<=total; i++) {
newArray = [newArray, array2[total-i]]
}
return newArray;
}
var finalArray = reverseIt(array);
alert(finalArray);