javascript - TypeError: (intermediate value).keys(...).map is not a function - Stack Overflow

I am getting a strange error, could somebody help me fix this out?const myArray = new Array(4).keys().m

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742294879a4416915.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信