You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
concat 函数类似于 ES 规范中的函数作用,用于进行数组拼接。
只是 lodash 在实现的过程中,不断践行自建基石的方针,也做了一些判断处理。
依赖
数组拷贝 copyArray
这个方法被用到,主要是考虑对原数组的保护。
/** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */functioncopyArray(source,array){varindex=-1,length=source.length;// 对array的存在性做一下判断array||(array=Array(length));while(++index<length){array[index]=source[index];}returnarray;}module.exports=copyArray;
数组后推入 arrayPush
继续自创push操作,通过操作数组下标进行赋值。
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
介绍
concat
函数类似于 ES 规范中的函数作用,用于进行数组拼接。只是
lodash
在实现的过程中,不断践行自建基石的方针,也做了一些判断处理。依赖
数组拷贝 copyArray
这个方法被用到,主要是考虑对原数组的保护。
数组后推入 arrayPush
继续自创push操作,通过操作数组下标进行赋值。
基础的数组扁平化操作 baseFlatten 👈 (划重点啦)
明显数组和类数组的 arguments 对象,可以通过遍历来展平。
另外在 ES6 中,可以设置 Symbol.isConcatSpreadable 的属性来表示该对象是否可以被展平。 Symbol.isConcatSpreadable 的值如果被设置为真值时,该对象是可以被展平的。
源码
总结
lodash
工具函数充分考虑了对传入参数的保护,尽可能小的影响参数。lodash
通过一些选项判断赋予函数更高的自由度和容错率。引用
本文使用「 署名 4.0 国际」创作共享协议。
本文同步发布于Littlewin's Blog,欢迎多多交流。
The text was updated successfully, but these errors were encountered: