简体   繁体   中英

Can't run simple code in console via node

I wrote simple code in JS

const a = [1, 2, [3, 4, [5, 6]]];

console.log(a.flat());

And I have error like this

console.log(a.flat());
          ^

TypeError: a.flat is not a function

I'm running code via node

node test.js

Do I need install some packages? I'm working on macOS.

Seems like Array.flat is not available in nodejs (v10).

Ah yes v11+ only - see compatability table: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

You most likely have an outdated version of Node.JS - as seen here , you need Node.JS 11 or newer.

Download the latest version of Node.JS from the website .

If you can't use/get the latest version, you could use the MDN polyfill which works for multiple levels of nesting:

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM