/* 杨辉三角 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 */ function yh(line) { var nowline = 0; function m(oldArr) { var arr = []; arr[0] = 1; if (!oldArr) { arr = [1]; } else { arr[oldArr.length] = 1; for (var i = 1; i < oldArr.length; i++) { arr[i] = oldArr[i-1] + oldArr[i]; } } nowline ++; console.log(arr); if (arr.length === line) { return arr; } return m(arr); } return m(); } yh(8);
// 找出字符串中重复最多的数字 const str = '1112223213'; const arr = []; const count = []; let max = 0; for (let i = 0; i < str.length; i++) { const index = arr.indexOf(str[i]); if (index === -1) { arr.push(str[i]); count.push(1); } else { count[index] ++; if (count[index] > max) { max = count[index]; } } } count.forEach((ele, index) => { if (ele === max) { console.log(`重复最多的数为${arr[index]},重复了${max}次`); } });
// 一串字符串中重复次最多的单词。 const str = 'a bb a ccc bb a cc bb'; const strArr = str.split(' '); const arr = []; const count = []; let max = 0; for (let i = 0; i < strArr.length; i++) { const index = arr.indexOf(strArr[i]); if (index === -1) { arr.push(strArr[i]); count.push(1); } else { count[index] ++; if (count[index] > max) { max = count[index]; } } } count.forEach((ele, index) => { if (ele === max) { console.log(`重复最多的单词为${arr[index]},重复次数为${max}`); } });
// 封装一个multi方法,能实现如此调用:multi(a)(b)(c)(d)(e)... // 并且返回的值为参数连乘的结果,即a*b*c*d*e...。 // 如multi(1)(3)(7) 得到21 function multi(num) { function fn(i) { num *= i; return fn; } fn.toString = () => { return num; } return fn; } console.log(multi(1)(3)(7));
// 数组去重 const arr = [1,2,3,3,3,1,2,2,4,5,1,5,6]; function fn(arr) { return arr.filter((ele, index) => // 遍历数组,当indexOf查找不到index + 1时返回该元素 arr.indexOf(ele, index + 1) < 0; ); } console.log(fn(arr)); // 或者 const arr = [1,2,3,3,3,1,2,2,4,5,1,5,6]; function fn(arr) { const newArr = []; arr.forEach(ele => { if (newArr.indexOf(ele) < 0) { newArr.push(ele); } }); return newArr; } console.log(fn(arr));
//或者
arr.filter((e, i) => arr.indexOf(e) === i);
深拷贝
const obj = { a: 1, c: [1, 2, 3, 4], d: [{ a: 1, b: 2 }, { c: 3, d: 4 }], e: {a: [1, 2 ,3], b: {a: 3}} } function deepCopy(item) { let newItem; if (Array.isArray(item)) { newItem = item.map(e => deepCopy(e)); } else if (typeof item === 'object') { newItem = {}; Object.keys(item).map(e => { newItem[e] = deepCopy(item[e]) }); } else { newItem = item; } return newItem; } const test = deepCopy(obj); JSON.stringify(test) === JSON.stringify(obj)