我正在尝试反转字符串并对 JavaScript 中的反转内容应用 join() 方法。当我在 join() 方法中使用“-”或任何其他符号时,连接可以正常工作。但是当我只使用 ("") 或 ("") 时,它只是连接原始数组而不是反向数组。请帮助我理解实际行为。
考虑下面的代码。
var a = [1,2,3]; //actual array
console.log(a.reverse().join("-")); // working as expected. output: "3-2-1"
console.log(a.reverse().join("")); //not working as expected. output:"123"
谢谢, 迪内什
最佳答案
Reverse改变原始数组
The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
在这种情况下,您可以制作浅拷贝,然后使用反向
var a = [1,2,3]; //actual array
console.log([...a].reverse().join("-")); // working as expected. output: "3-2-1"
console.log([...a].reverse().join(""));
关于JavaScript:对于 join() 方法中的空标记,数组反向和连接无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55574226/