.map() 改变初始值

时间:2021-01-21 15:14:03

标签: javascript arrays luhn

我正在编写一个脚本,该脚本使用 Luhn 算法将无效的信用卡号转换为有效的信用卡号。

脚本如下:

const array1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
const array2 = [5, 7, 9, 5, 5, 9, 3, 3, 9, 2, 1, 3, 4, 6, 4, 3];
const array3 = [3, 7, 5, 7, 9, 6, 0, 8, 4, 4, 5, 9, 9, 1, 4];

const batch = [array1, array2, array3];


const validateNumber = array => {
    let x = true;

    let checkArray = array.reduceRight((accumulator, currentValue) => {
        if (x === true) {
            x = false;
        } else {
            currentValue *= 2;
            if (currentValue > 9) currentValue -= 9;
            x = true;
        }
        return accumulator + currentValue;
    }, 0);

    return checkArray %= 10;
};


const makeNumbersValid = (() => {
    const newArray = batch.map(current => {
        const getResult = validateNumber(current);

        if (getResult <= current[current.length - 1]) {
            current[current.length - 1]  =  current[current.length - 1] - getResult;

        } else if (getResult > current[current.length - 1]) {
            current[current.length - 1]  =  current[current.length - 1] + (10 - getResult);
        }

        return current;
    });

    return newArray;
})();

console.log(array1); // logs [.., 0] instead of [.., 5]

代码改变了初始数组,我怀疑在 current 语句中为 if 分配新值时会发生这种情况。

我尝试了多种解决方案,包括将 .map() 更改为 .forEach(),使用 newArray.push() 代替 current[] = ...,以及制作 batch 的副本,但没有一个解决了问题。

我还研究了以下问题:Why does map mutate array of objects?Using map in the main array。但它们专门针对数组内的对象,我找不到任何涵盖“普通”数组的问题。

欢迎提供任何答案。

编辑:

也从我没有投入足够研究工作的错误中吸取教训,这是我使用 lodash 从 Copy array by value 问题中提出的解决方案:

const batchClone = _.cloneDeep(batch)

0 个答案:

没有答案