[英]I can't get my reversed array to print into the console.log calling it
我终于能够复制和反转数组,而不是替换和反转数组。 接下来我可以尝试什么?
function copyAndReverseArray(array) { array.slice(0).reverse().map(function(reversed) { return reversed; }); } //Don't change below this line const original = [1, 2, 9, 8]; const reversed = copyAndReverseArray(original); console.log(original, '<--this should be [1, 2, 9, 8]'); console.log(reversed, '<--this should be [8, 9, 2, 1]');
我知道我的反向函数正在工作,当我直接在函数中 console.log 反向数组时。
function copyAndReverseArray(array) { array.slice(0).reverse().map(function(reversed) { console.log(reversed); return reversed; }); } //Don't change below this line const original = [1, 2, 9, 8]; const reversed = copyAndReverseArray(original); console.log(original, '<--this should be [1, 2, 9, 8]'); console.log(reversed, '<--this should be [8, 9, 2, 1]');
如何在不更改“//不要在此行下方更改”下方的代码的情况下从console.log中“反转”以在底部调用它?
你的代码没问题,只是不要忘记范围理论。
当您观察并返回反向列表时,映射实际上反转了列表,但该结果仅存在于功能范围(copyAndReverseArray)中,因此您需要再次返回该值以将其置于上级范围:在这种情况下为全局范围。 如果不返回结果,您将继续拥有未定义的值
所以,试试这个:
function copyAndReverseArray(array){
return array.slice(0).reverse().map(function (reversed) {
return reversed
});
}
然后,您可以将结果分配给您一直在尝试的 var
const original = [1, 2, 9, 8];
const reversed = copyAndReverseArray(original);
console.log(original, '<--this should be [1, 2, 9, 8]');
console.log(reversed, '<--this should be [8, 9, 2, 1]');
您需要在copyAndReverse
return
您从map
回调中return
的内容。
function copyAndReverseArray(array){
return array.slice(0).reverse().map(function (reversed) {
return reversed;
});
}
如果您需要更简单的解决方案,只需像这样应用扩展运算符语法
function copyAndReverseArray(array) {
return [...array].reverse();
}
就像第一种方法一样,这不会更改您的原始数组(您作为参数传递的数组)。
为了完整起见,请注意这一点:
function copyAndReverseArray(array) {
return array.reverse();
}
因为它也会影响原始数组,即您作为参数传递的数组。 例如:
var arr1 = [1, 2, 3];
var arr2 = copyAndReverseArray(arr1);
//Now, arr1 == arr2. Check it with:
console.log(arr1);
console.log(arr2);
你的代码几乎是正确的。 你缺少return
。 你的map()
也没有做任何事情。 您可以安全地删除map()
部分。
function copyAndReverseArray(array){ return array.slice(0).reverse(); } //Don't change below this line const original = [1, 2, 9, 8]; const reversed = copyAndReverseArray(original); console.log(original, '<--this should be [1, 2, 9, 8]'); console.log(reversed, '<--this should be [8, 9, 2, 1]');
尝试使用数组展开运算符克隆原始数组而不对其进行变异。
function copyAndReverseArray(array) {
return [...array].reverse();
};
这对你有用吗?
function copyAndReverseArray(array){
reversedArray = Object.assign([],array)
return reversedArray.reverse()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.