reduce
对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。
1234567891011121314var arr = [5, 2, 3, 4, 1];var bb = arr.reduce(function (x, y) {return x + y;})var aa = arr.reduce(function (x, y) {return x * y;});var cc = arr.sort(function (x, y) {return x - y;});console.log(aa);console.log(bb);console.log(cc);数组去重
123456789101112var arr = [1, 2, 3, 4, 5, 6, 3, 4, 5, 6, 3, 2, 10, 4, 2];Array.prototype.unique = function () {var res = [];this.forEach(function (ele) {if (res.indexOf(ele) == -1) {res.push(ele)}})return res;}console.log(arr.unique())找对象数组中对应元素
1234567891011121314151617181920212223242526var father = [{id: 1,name: "大娃",child: [{ id: 2, name: '大娃的大儿子' }, { id: 3, name: '大娃的二儿子' }]},{id: 4,name: "二娃",child: [{ id: 5, name: '二娃的大儿子' }, { id: 6, name: '二娃的二儿子' }]},{id: 7,name: "三娃",child: [{ id: 8, name: '三娃的大儿子' }, { id: 9, name: '三娃的二儿子' }]}];function fn(id) {father.forEach(function (ele) {ele.child.forEach(function (val) {val.id === id && console.log(ele.name);})})}fn(3);