[英]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.