声明循环时需要记住的变量的正确范围是什么?

What is the correct scope to declare a variable that needs to be remembered while looping?

这里是 JavaScript 的初学者。下面是我刚刚完成的一门课程的 JS 挑战。挑战:

Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], make a function that organizes these into individual array that is ordered. For example answer(ArrayFromAbove) should return: [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]

我的解决方案:

let originalArray = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];

const compareFunction = ((a, b) => {
    return a-b;
});

let counter = 1;

const groupFunction = (currentValue, index, arr) => {
    nextNumber = arr[index + 1];
    if (currentValue === nextNumber){
        counter++;
    } else {
        if (counter > 1){
            let filledArray = new Array(counter).fill(currentValue);
            counter = 1;
            return filledArray;
        } else {
            return currentValue;
        }
    }  
};

const filterFunction =  (currentValue) => {
    return currentValue !== undefined;
}

const finalFunction = (arr) => {
    arr.sort(compareFunction);
    let groupedArray = arr.map(groupFunction);
    let finalArray = groupedArray.filter(filterFunction);
    return finalArray;
}

finalFunction (originalArray);

一切 returns 正确,但我的印象是声明全局变量是不好的做法。使用我的“计数器”变量,如果我在 groupFunction 中分配它,计数器会重置数组中的每个循环,使其无用。把这个变量放在哪里合适?是否有另一种方法/方法更适合所有问题?谢谢!

在我看来,你的代码很难读,如果你能以某种方式重写它可能会更好,但我会把它留给你。要删除此全局变量,您可以做的一件事是使用称为高阶函数的概念。

const higherOrderFunction = () => {
    let counter = 1;
    const groupFunction = (currentValue, index, arr) => {
        nextNumber = arr[index + 1];
        if (currentValue === nextNumber){
            counter++;
        } else {
            if (counter > 1){
                let filledArray = new Array(counter).fill(currentValue);
                counter = 1;
                return filledArray;
            } else {
                return currentValue;
            }
        }
    }
    return groupFunction; 
};

然后您可以通过调用高阶函数来访问您的 groupFunction, 但该变量不会污染您的全局范围:

let groupFunction = higherOrderFunction()

这是一个更简短的方法,我知道作为初学者,如果您还没有了解它,会让您搜索以了解所使用的一些东西的作用。

保持好奇。

const finalFunction = (arr) => {
  const map = arr.reduce((acc, curr) => {
    acc[curr] = (acc[curr] || 0) + 1;
    return acc;
  }, {});
  return Object.keys(map)
    .sort((a, b) => a - b)
    .reduce((acc, val) => {
      const value = Number(val);
      acc.push(map[val] > 1 ? Array(map[val]).fill(value) : value);
      return acc;
    }, []);
};

还有一个:

const finalFunction = (arr) =>  arr.sort((a, b) => a - b)
    .reduce((acc, curr) => {
      const last = acc.pop();
      return curr === last
        ? [...acc, [curr, curr]]
        : last && curr === last[0]
        ? [...acc, [...last, curr]]
        : [...acc, ...(last ? [last] : []), curr];
    }, []);