Home > database >  Is it possible to have multiple keys point to the same object?
Is it possible to have multiple keys point to the same object?

Time:11-02

Basically I want to call myList[i] and get the same value for i = 1, 2, 3, 4 then a second value for 5, 6, 7, 8 and so on. I don't really want to copy-paste the value for 1 into 2, 3, 4.

CodePudding user response:

You can try using this -

myList[Math.floor((i-1)/4)]

where i = 1, 2, 3, 4 ...

But if i starts from 0, then

myList[Math.floor(i/4)]

Adjust the /- 1 according to your requirements.

Where 4 is the block size to which you need to divide the array with.

CodePudding user response:

You can use an array of objects

const arr = [...Array(4).fill({ value: 1 }), ...Array(4).fill({ value: 3 })];

console.log(arr[0].value);
console.log(arr[2].value);
console.log(arr[4].value);
console.log(arr[6].value);
arr[0].value = 2;
console.log(arr[0].value);
console.log(arr[2].value);
console.log(arr[4].value);
console.log(arr[6].value);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Each element is a reference to the same object.

That's not possible with an array of primitives.

  • Related