微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.map() 改变初始值

如何解决.map() 改变初始值

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

脚本如下:

const array1 = [4,5,3,2,7,8,1,9,5];
const array2 = [5,4,6,3];
const array3 = [3,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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。