Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

465
Views
.flat() no es una función, ¿qué pasa?

El siguiente código

 function steamrollArray(arr) { // I'm a steamroller, baby return arr.flat(); } steamrollArray([1, [2], [3, [[4]]]]);

devoluciones

arr.flat no es una función

Lo probé en Firefox y Chrome v67 y ha ocurrido el mismo resultado.

¿Qué ocurre?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

El método flat aún no está implementado en los navegadores comunes (solo Chrome v69, Firefox Nightly y Opera 56). Es una característica experimental. Por lo tanto, no puede usarlo todavía .

Es posible que desee tener su propia función flat en su lugar:

 Object.defineProperty(Array.prototype, 'flat', { value: function(depth = 1) { return this.reduce(function (flat, toFlatten) { return flat.concat((Array.isArray(toFlatten) && (depth>1)) ? toFlatten.flat(depth-1) : toFlatten); }, []); } }); console.log( [1, [2], [3, [[4]]]].flat(2) );

El código fue tomado de aquí por Noah Freitas implementado originalmente para aplanar la matriz sin especificar la depth .

over 4 years ago · Santiago Trujillo Report

0

Esto también puede funcionar.

 let arr = [ [1,2,3], [2,3,4] ]; console.log([].concat(...arr))

O para navegadores más antiguos,

 [].concat.apply([], arr);
over 4 years ago · Santiago Trujillo Report

0

Array.flat no es compatible con su navegador. A continuación se presentan dos formas de implementarlo.

Como función, la variable de depth especifica la profundidad a la que se debe aplanar la estructura de la matriz de input (el valor predeterminado es 1; use Infinity para profundizar tanto como sea posible) mientras que la stack es la matriz aplanada, se pasa por referencia en llamadas recursivas y finalmente se devuelve.

 function flat(input, depth = 1, stack = []) { for (let item of input) { if (item instanceof Array && depth > 0) { flat(item, depth - 1, stack); } else { stack.push(item); } } return stack; }

Como Polyfill, extendiendo Array.prototype si prefiere la sintaxis arr.flat() :

 if (!Array.prototype.flat) { Object.defineProperty(Array.prototype, 'flat', { value: function(depth = 1, stack = []) { for (let item of this) { if (item instanceof Array && depth > 0) { item.flat(depth - 1, stack); } else { stack.push(item); } } return stack; } }); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!