我无法获取反转数组以打印到console.log中调用它

我终于能够复制并反转阵列,而不是替换并反转阵列。我接下来可以尝试什么?

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,8]');
console.log(reversed,'<--this should be [8,1]');

当我在控制台中直接在函数中记录反向数组时,我知道反向函数正在工作。

function copyAndReverseArray(array) {
  array.slice(0).reverse().map(function(reversed) {
    console.log(reversed);
    return reversed;
  });
}

//Don't change below this line
const original = [1,1]');

如何在不更改“ //不要在此行以下更改”下面的代码的情况下,从console.log的底部调用它来“反转”?

charmprefect 回答:我无法获取反转数组以打印到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,8]');
console.log(reversed,'<--this should be [8,1]');
,

您需要在return中通过copyAndReverse回调return中的map

function copyAndReverseArray(array){
  return array.slice(0).reverse().map(function (reversed) {
     return reversed;
  });
}

如果您需要更简单的解决方案,只需应用spread operator  像这样的语法

function copyAndReverseArray(array) {
  return [...array].reverse();
}

就像第一种方法一样,这不会更改原始数组(作为参数传递的数组)。

出于完整性考虑,请当心:

function copyAndReverseArray(array) {
  return array.reverse();
}

由于它也会影响原始数组,因此您将其作为参数传递。例如:

var arr1 = [1,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,1]');

,

尝试使用数组传播运算符克隆原始数组而不对其进行突变。

function copyAndReverseArray(array) {
  return [...array].reverse();
};
,

这对您有用吗?

function copyAndReverseArray(array){
    reversedArray = Object.assign([],array)
    return reversedArray.reverse()
}
本文链接:https://www.f2er.com/3025317.html

大家都在问