我需要编写一个交换函数。假设示例输入为 [1,2]。这就是我现在所拥有的:
function swapValues() {
var args = Array.prototype.slice.call(arguments);
console.log(args[0]);
var temp = args[0];
args[0] = args[1];
args[1] = temp;
return args;
}
我没有获得所需的交换功能,因此我将 console.log 语句放入其中以查看发生了什么。问题是我正在将 [1 , 2] 打印到控制台,但我只期待一个。返回的值不会交换。
最佳答案
为什么不使用Array.prototype.reverse
?我会这样做:
function swapValues() {
var args = Array.prototype.slice.call(arguments);
return args.reverse();
}
关于javascript - 将参数转换为数组但无法访问单个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518764/