Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
JavaScript: Index object by array?

I'm storing some collision squares with properties in my JavaScript code. The easiest way seems to be an object using arrays as the index. My code should look something like this:

// left, top, width, height
const array = [0, 0, 8, 16];
var rectangles = {};
rectangles[array] = {foo: bar};

Wanted to make sure this is a valid and sound method. I remember people saying objects in JS are always indexed by string, this might not convert accordingly then. It thus seems safer to use a string (const s = array[0] + " " + array[1] + " " + array[2] + " " + array[3]) but I was hoping that doing it this way might allow me to extract entries by specifying their array so I wouldn't need my own string separator function to match the values.

// Obviously I'd use a more complex function to get the values I need
const this_rectangle = rectangles[[0, 0, 8, 16]];
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

How about you use a WeakMap :D

// left, top, width, height
const array = [0, 0, 8, 16];
var rectangles=new WeakMap(); //declaration
rectangles.set(array,{foo:"bar"}); //setting

//example
console.log( rectangles.get(array) ); //getting

about 4 years ago · Juan Pablo Isaza Relatório

0

Objects are indeed indexed by string exclusively. Found a convenient solution with this in mind:

const array = [0, 0, 8, 16].toString();
rectangles[array] = {foo: "bar"};

And to extract the positions back into an array when iterating through rectangles:

for(let pos in rectangle) {
    const data = rectangle[pos];
    const poses = pos.split(",");
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda