flat()方法用于递归铺平多维数组,默认只铺平一层,可通过参数控制深度,如flat(2)铺平两层,flat(infinity)可完全铺平;1. flat()返回新数组,不修改原数组;2. 处理稀疏数组时会自动移除空槽;3. 非数组元素如字符串会被直接添加到结果中;4. 性能方面,大型或深度嵌套数组应避免不必要的深度铺平,建议按需铺平并测试性能;5. flatmap()先对每个元素执行映射函数再铺平一层,等价于map后接flat(),但更高效,适用于如字符串分割为单词等场景。
核心在于
flat()
flat()
解决方案
直接上代码,更清晰:
const arr = [1, [2, [3, [4, 5]]], 6]; // 默认铺平一层 console.log(arr.flat()); // [1, 2, [3, [4, 5]], 6] // 铺平两层 console.log(arr.flat(2)); // [1, 2, 3, [4, 5], 6] // 铺平到无限深度 console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6] // 对于稀疏数组,flat() 会移除空槽 const sparseArray = [1, , 3, [4, , 6]]; console.log(sparseArray.flat()); // [1, 3, 4, 6]
flat()
flat()
reduce()
concat()
如何处理数组中包含非数组元素的情况?
如果你的多维数组中包含非数组元素,
flat()
const mixedArray = [1, [2, 'hello', [3, 4]], 5]; console.log(mixedArray.flat(Infinity)); // [1, 2, "hello", 3, 4, 5]
字符串'hello'被直接添加到结果数组中,没有任何问题。这使得
flat()
flat()
flat()
一些建议:
flat(Infinity)
for
flat()
console.time()
console.timeEnd()
flat()
flatMap()
flat()
flatMap()
map()
flat()
const arr = [1, 2, 3]; // 使用 map() 和 flat() const result1 = arr.map(x => [x * 2]).flat(); console.log(result1); // [2, 4, 6] // 使用 flatMap() const result2 = arr.flatMap(x => [x * 2]); console.log(result2); // [2, 4, 6]
flatMap()
flat()
flatMap()
const sentences = ["hello world", "how are you"]; const words = sentences.flatMap(sentence => sentence.split(" ")); console.log(words); // ["hello", "world", "how", "are", "you"]
以上就是js 如何使用flat将多维数组转为一维的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号