函数式编程 顾名思义就是不依赖外界影响而变化,只依靠自身的输入和输出来得到自己想要的
例子1
var arr = [{name:'123'}] function add(_arr) { var obj= {name: 'cst'} var newArr = [] for(var i = 0; i < _arr.length; i++) { newArr[i] = _arr[i] } newArr.push(obj) return newArr } var newArr = add(arr) arr => // [{name:'123'}] newArr => // [{name: '123'}, {name: 'cst'}]
改变新创建出来的newAr newArr[0].name = 'ccc' =====>// "ccc" 打印arr arr[0].name // 会发现输出也是"ccc" ------- 改变原来的 arr 的name值 arr[0].name='aaaaaa' =======> // 'aaaaaa' 打印newArr newArr[0].name // 会发现输出的结构是arr改变后的值 即 'aaaaaa'
上面一个例子已经很接近纯函数了,但是,如果改变改变arr或newArr共同的值 name时候都会影响到另一个值的改变
下面是优化后的
function isObject(obj) { return typeof obj === "object" && obj != null; } const deepClone = (source, hash = new WeakMap()) => { if (!isObject(source)) return source; if (hash.has(source)) return has.get(source); const target = Array.isArray(source) ? [] : {}; hash.set(source, target); for (key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = deepClone(source[key], hash); } } return target; }; var arrs = [{ name: "123" }]; function add(_arr) { var obj = { name: "cst" }; var newArrs = []; for (var i = 0; i < _arr.length; i++) { newArrs[i] = deepClone(_arr[i]); // 使用deepClone() 方法进行深度拷贝 } newArrs.push(obj); return newArrs; }
例子2: 使用map来创建新的值
var rooms = ['h1','h2','h3','h4'] var newRooms = rooms.map(function(rm) { if(rm == 'h3') { return 'h5' }else { return rm } }) rooms => // ['h1','h2','h3','h4'] newRooms => //["h1", "h2", "h5", "h4"]