多维数组转一维数组

  1. function flag(array) {
  2. let length = array.length;
  3. if (length === 0) return array;
  4. let ret = [];
  5. for (let item of array) {
  6. if (item.constructor === Array) {
  7. ret = ret.concat(flag(item));
  8. } else {
  9. ret.push(item);
  10. }
  11. }
  12. return ret;
  13. }
  14. var mulitArray = [[1, [45, 23, 44], 1], 4, 25];
  15. flag(mulitArray);
  16. // [ 1, 45, 23, 44, 1, 4, 25 ]

两个数组的交集

  1. function intersection(array1 = [], array2 = []) {
  2. return array1.filter(item => array2.includes(item));
  3. }
  4. var array1 = [1, 2, 3, 4, 5];
  5. var array2 = [4, 5, 6, 53];
  6. intersection(array1, array2);
  7. // [ 4, 5 ]

深拷贝

  1. function deepCopy(target) {
  2. if (typeof target !== "object") return target;
  3. let ret;
  4. if (Array.isArray(target)) {
  5. ret = target.map(item => deepCopy(item));
  6. } else {
  7. ret = {};
  8. Object.keys(target).forEach(item => {
  9. ret[item] = deepCopy(target[item]);
  10. });
  11. }
  12. return ret;
  13. }
  14. var data = [1, 2, 3, { name: "xiaoming" }];
  15. // var data = { name: "小红", age: [23, 4] };
  16. // var data = [1, 2, 3, [4, 1, 5]];
  17. var result = deepCopy(data);