You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python的list()、filter()、lambda在JavaScript中的等价实现方法

Python转JavaScript:list()、filter()、lambda的等价实现

原Python代码功能

这段Python代码用于从列表中筛选出满足「自身加10或减10也存在于原列表」的元素:

my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]
new_list = list(filter(lambda x: x + 10 in my_list or x - 10 in my_list, my_list))

各元素的JavaScript等价写法

1. lambda → 箭头函数

Python的lambda是匿名函数,JavaScript中最直接的等价写法是箭头函数,用来定义筛选的判断逻辑:

  • Python:lambda x: x + 10 in my_list or x - 10 in my_list
  • JavaScript:x => myList.includes(x + 10) || myList.includes(x - 10)

2. filter() → 数组的filter()方法

JavaScript数组原生自带filter()方法,功能和Python的filter()完全一致:遍历数组,将符合判断函数条件的元素组成新数组返回。

3. list() → 无需额外转换

Python中filter()返回的是迭代器,必须用list()转为列表;而JavaScript的filter()方法直接返回数组,所以不需要额外的转换步骤。

完整JavaScript实现

const myList = [18, 19, 20, 27, 28, 29, 38, 39, 40];
const newList = myList.filter(x => myList.includes(x + 10) || myList.includes(x - 10));

console.log(newList); // 输出:[18, 20, 27, 29, 38, 40]

内容的提问来源于stack exchange,提问作者Bary Simmons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:31:06