简体   繁体   English

JavaScript是否具有与LINQ的Select语句类似的功能?

[英]Does JavaScript have a similar capability as LINQ's Select statement?

Say I have an array of window objects and each has an ID property and I need to get an array of those IDs. 假设我有一个窗口对象数组,每个对象都有一个ID属性,我需要获取这些ID的数组。

In LINQ, I would just do this... 在LINQ中,我只会这样做...

var ids = windows.Select(window => window.id).ToArray();

Nice and simple. 漂亮又简单。 But in Javascript, I've been doing this... 但是在Javascript中,我一直在做...

var ids = [];

for(i = 0; i < windows.length; i++)
{
    var window = windows[i];
    ids.push(window.id);
}

I'm just wondering if there's a simpler/easier way in Javascript, similar to LINQ's elegant solution. 我只是想知道Java语言中是否有更简单/更简便的方法,类似于LINQ的优雅解决方案。

If you are happy with IE8 and above support, array.map() is a comparable option: 如果您对IE8及以上版本的支持感到满意,可以使用array.map()作为可比较的选择:

var ids = windows.map(function(val) {
    return val.id;
});

This of course becomes even more succinct (and similar to LINQ) if using ES6 fat arrow functions, although this will require a transpiler if supporting non-cutting edge browsers: 如果使用ES6粗箭头功能,这当然会变得更加简洁(与LINQ相似),但是如果支持非尖端浏览器,则需要编译器:

var ids = windows.map(x => x.id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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