JavaScript 的 数组分区
等级 4296 次按键
分区根据谓词函数将数组分成两个数组。
JavaScript 代码
// 使用reduce的分区函数1const partition = (arr, predicate) => { // 用两个空数组作为初始值进行reduce2 return arr.reduce( // 将累加器解构为[pass, fail]3 ([pass, fail], item) => // 如果谓词为true,添加到pass;否则添加到fail4 predicate(item) ? [[...pass, item], fail] : [pass, [...fail, item]],5 [[], []]6 );7};// 测试数组8const nums = [1, 2, 3, 4, 5, 6];// 分成偶数和奇数9const [evens, odds] = partition(nums, n => n % 2 === 0);// 打印偶数: [2, 4, 6]10console.log(evens);// 打印奇数: [1, 3, 5]11console.log(odds);运行结果
[ 2, 4, 6 ] [ 1, 3, 5 ]
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
,× 16[× 10]× 10.× 9=× 9(× 7)× 7;× 6>× 3:× 1