admin管理员组

文章数量:1332896

I am getting a strange error, could somebody help me fix this out?

const myArray = new Array(4)
    .keys()
    .map((v, i) => (
          console.log('print:', v, i)
      )
    )
console.log('myArray print: ', myArray);

I am getting this error:

TypeError: (intermediate value).keys(...).map is not a function

update:

i want to use the i to look up some stuff from another existing array.

const myArray = new Array(4)
    .keys()
    .map((v, i) => ({
      name: i
      })
    )
console.log('myArray print: ', myArray);

edit:

this question is not a duplicate, It is trying to iterate over a certain number and create a new object using the iterations.

I am getting a strange error, could somebody help me fix this out?

const myArray = new Array(4)
    .keys()
    .map((v, i) => (
          console.log('print:', v, i)
      )
    )
console.log('myArray print: ', myArray);

I am getting this error:

TypeError: (intermediate value).keys(...).map is not a function

update:

i want to use the i to look up some stuff from another existing array.

const myArray = new Array(4)
    .keys()
    .map((v, i) => ({
      name: i
      })
    )
console.log('myArray print: ', myArray);

edit:

this question is not a duplicate, It is trying to iterate over a certain number and create a new object using the iterations.

Share edited Dec 6, 2017 at 10:16 moaningalways asked Dec 6, 2017 at 10:10 moaningalwaysmoaningalways 4611 gold badge10 silver badges21 bronze badges 13
  • the function keys when applied to the array returns an object, and the map function is not available for objects. – Daksh M. Commented Dec 6, 2017 at 10:13
  • What do you want to do with the code above? – Faly Commented Dec 6, 2017 at 10:13
  • Same issue and solution as the dupe target, except that keys is an iterator object instead of a HTML collection. – Cerbrus Commented Dec 6, 2017 at 10:14
  • You can use entries() instead of map() – Alexis Commented Dec 6, 2017 at 10:15
  • @Faly please see the update – moaningalways Commented Dec 6, 2017 at 10:17
 |  Show 8 more ments

2 Answers 2

Reset to default 5

Array.keys() returns an iterator Object which is an object and does not have a property map in it. You can convert it to do

const myArray = [...new Array(4).keys()].map((v, i) => ({
      name: i
      })
    )
console.log('myArray print: ', myArray);

You can use Array.from to get the expected output:

var myArray = Array.from(Array(4), (value, index) => ({ name: index}));
console.log('myArray print: ', myArray);

本文标签: javascriptTypeError (intermediate value)keys()map is not a functionStack Overflow