12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-18 16:47:32
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
JavaScript 列表推导是一种非常方便的语法,它可以处理一些比较复杂的数据操作,使得代码更加简洁易读。它在 Python 中也有类似的语法,被称为 List Comprehension。下面我们来详
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];const evenSquares = [num * num for (num of nums) if (num % 2 === 0)];console.log(evenSquares); // [4, 16, 36, 64, 100]
上面的代码中,我们定义了一个数组 nums,然后使用列表推导式找到了所有的偶数,并将其平方存放在了 evenSquares 数组中。列表推导式的结构是 [表达式 for 变量 of 列表 if 条件],也就是“变量 of 列表”表示循环,if 条件表示筛选,表达式表示计算。下面我们再来看一些其他的例子,来更好的理解列表推导。获取数组中的所有字符串的长度:const strs = ['hello', 'world', 'test', 'hello world'];const strLengths = [str.length for (str of strs) if (typeof str === 'string')];console.log(strLengths); // [5, 5, 4, 11]
上面的代码中,我们定义了一个数组 strs,然后使用列表推导式找到了所有的字符串,并获取了它们的长度存放在了 strLengths 数组中。获取数组中所有最大值:const nestedArr = [[1, 2, 3], [4, 5], [6, 7, 8, 9]];const maxValues = [Math.max(...arr) for (arr of nestedArr)];console.log(maxValues); // [3, 5, 9]
在上面的代码中,我们定义了一个嵌套数组 nestedArr,然后使用列表推导式在每个子数组中找到了最大值,并将其存放在 maxValues 数组中。另外,列表推导也可以使用嵌套的循环,以此从多个列表中快速推导出新的列表。比如我们需要从两个数组中获取所有的组合:const colors = ['red', 'blue', 'green'];const sizes = ['small', 'medium', 'large'];const combinations = [[color, size] for (color of colors) for (size of sizes)];console.log(combinations); // [// ['red', 'small'], ['red', 'medium'], ['red', 'large'],// ['blue', 'small'], ['blue', 'medium'], ['blue', 'large'],// ['green', 'small'], ['green', 'medium'], ['green', 'large']// ]
上面的代码中,我们定义了两个数组 colors 和 sizes,然后使用两个循环嵌套,快速从两个数组中获取了所有的组合并存放在了 combinations 数组中。综上,JavaScript 列表推导是一个非常方便的语法,在处理一些复杂的数据结构操作时,能够使代码更加简洁易读。同时,列表推导也支持嵌套的循环,可以使用 if 条件快速筛选出需要的数据,让开发更加高效。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19