柒七 2022-05-02 22:12:51
const spreadableSymbol = Symbol.isConcatSpreadable const isFlattenable = (value) => { return Array.isArray(value) || (typeof value == 'object' && value !== null && Object.prototype.toString.call(value) === '[object Arguments]') || !!(spreadableSymbol && value && value[spreadableSymbol]) } /** * flatten的基本实现,具体可以参考lodash库的flatten源码 * @param array 需要展开的数组 * @param depth 展开深度 * @param predicate 迭代时需要调用的函数 * @param isStrict 限制通过`predicate`函数检查的值 * @param result 初始结果值 * @returns {Array} 返回展开后的数组 */ function flatten(array, depth, predicate, isStrict, result) { predicate || (predicate = isFlattenable) result || (result = []) if (array == null) { return result } for (const value of array) { if (depth > 0 && predicate(value)) { if (depth > 1) { flatten(value, depth - 1, predicate, isStrict, result) } else { result.push(...value) } } else if (!isStrict) { result[result.length] = value } } return result } flatten([1, 2, 3, [4, 5, [6]]], 2) // [1, 2, 3, 4, 5, 6]
- 共 1 页
- 1
indexOf用于查找基本数据类型的下标,内部采用全等(===)来进行判断,
findIndex用于查找复杂数据类型的下标,arr.findIndex(item=>{item.id==1})
第163题:indexOf 和 findIndex 的区别