Javascript array map to propery (item => item[prop])?

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

Im learning javascript and looking over some code and ran into this:

array.map(item => item[prop]) where prop may be something like 'id' or something.

I haven't been able to find an actual example of this on the web. So I tried just doing something like this:

property = 'id'; var arr = [1,2,3,4]; var something = arr.map(item => item[property]); console.log(something); 

This doesn't work however. And I can't seem to find an example on the web. Is this a new type of syntax for the map function?

回答1:

The "arrow function" is a shorthand way of writing functions.

item => item[property] 

It is (mostly) equivalent to writing:

function(item){     return item[property]; } 

Your arr array contains numbers, so in the function item will be a number. Numbers do not have an 'id' property, so that's why it "doesn't work".

Consider if you had something like:

var prop = 'id'; var arr = [{id:1, name:"one"}, {id:2, name:"two"}]; var something = arr.map(item => item[prop]); console.log(something); 

something would end up being [1, 2].



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!