How to access array in circular manner in JavaScript

前端 未结 6 427
攒了一身酷
攒了一身酷 2020-12-05 08:40

I have an array like [A,B,C,D]. I want to access that array within a for loop like as

var arr = [A,B,C,D];

var len = arr.len;
for(var i = 0;i&         


        
6条回答
  •  执笔经年
    2020-12-05 08:58

    Answering to the main question, someone can access an array in a circular manner using modular arithmetic. That can be achieved in JavaScript with the modulus operator (%) and a workaround.

    Given an array arr of a length n and a value val stored in it that will be obtained through an access index i, the circular manner, and safer way, to access the array, disregarding the value and sign of i, would be:

    let val = arr[(i % n + n) % n];
    

    This little trick is necessary -- someone can not use the modulus result straightforwardly -- because JavaScript always evaluates a modulus operation as the remainder of the division between dividend (the first operand) and divisor (the second operand) disconsidering their signs but assigning to the remainder the sign of the dividend. That behavior does not always result in the desired "wrap around" effect of the modular arithmetic and could result in a wrong access of a negative position of the array.

    References for more information:

    1. https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic
    2. https://en.wikipedia.org/wiki/Modular_arithmetic
    3. https://en.wikipedia.org/wiki/Modulo_operation
    4. https://dev.to/maurobringolf/a-neat-trick-to-compute-modulo-of-negative-numbers-111e

提交回复
热议问题