Javascript数组映射到propery(item => item [prop])? [英] Javascript array map to propery (item => item[prop])?

查看:99
本文介绍了Javascript数组映射到propery(item => item [prop])?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习javascript并查看一些代码并遇到这个问题:

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

array.map(item => item [prop]) 其中道具可能是'id'之类的东西。

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

但是这不起作用。我似乎无法在网上找到一个例子。这是map函数的一种新语法吗?

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?

推荐答案

箭头函数是编写函数的简写方法。

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

item => item[property]

它(大部分)相当于写作:

It is (mostly) equivalent to writing:

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

您的 arr 数组包含数字,因此在函数 item 中将是数字。数字没有'id'属性,这就是为什么它不起作用。

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

某些东西最终将 [1,2]

这篇关于Javascript数组映射到propery(item => item [prop])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆