我正在研究FCC挑战,学习JS。这是挑战我的链接。
我有点解决了它,但是一个应该起作用的代码,而另一种代码则不起作用,我认为它们本质上是相同的。
这是有效的代码:
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
return [].concat(arr).sort(function(a, b) {
return a - b;
});
// Add your code above this line
}
nonMutatingSort(globalArray);
此代码不起作用
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
let newArr = [];
newArr.concat(arr);
return newArr.sort(function(a,b){return a-b;});
// Add your code above this line
}
nonMutatingSort(globalArray);
我的问题本质上是为什么?两个代码连接到新数组,两个函数都应返回排序的数组。
但是,在第一个功能中,串联失败了...它仅返回空ARR。为什么?我感到很困惑。它在功能之外工作,但是功能不足。
concat
不会突变任何现有的数组(要么调用函数的数组,要么在参数列表中的数组(s((。调用concat
时,您返回a new 数组。因此,独立语句
newArr.concat(arr);
什么都不做 - 您将newArr
与arr
串联,创建一个新的组合数组,但是该组合的数组未分配给任何内容;它被评估然后丢弃。
const arr1 = ['a'];
const arr2 = ['b'];
// Does not do anything by itself:
arr1.concat(arr2);
console.log(arr1);
console.log(arr2);
而是将结果分配给newArr
:
newArr = newArr.concat(arr);
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
let newArr = [];
newArr = newArr.concat(arr);
return newArr.sort(function(a,b){return a-b;});
// Add your code above this line
}
console.log(nonMutatingSort(globalArray));
// Original array is not mutated:
console.log(globalArray);
或,避免完全避免newArr
的初始声明,然后使用您的原始代码(我更喜欢(。实际上,要变得更简短,您可能只是slice
原始数组,而不是明确创建一个空数字:
var globalArray = [5, 6, 3, 2, 9];
const nonMutatingSort = arr => arr.slice().sort((a, b) => a - b);
console.log(nonMutatingSort(globalArray));
concat方法返回一个新数组,因此您需要保存在同一变量或其他变量中。在您的情况下:
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
let newArr = [];
newArr = newArr.concat(arr); //here it will return new new which you need to save
return newArr.sort(function(a,b){return a-b;});
// Add your code above this line
}
nonMutatingSort(globalArray);