前端面试题之数据处理

1. 实现数组的乱序输出

有正序和倒序两种:

const arr = [1, 2, 3, 4, 5];

// for (let i = 0; i < arr.length; i++) {
//   const randomIndex = Math.round((Math.random() * (arr.length - 1 - i))) + i;
//   [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
// }

let len = arr.length;

for (let i = len - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [arr[i], arr[j]] = [arr[j], arr[i]];
}

console.log(arr);

2. 实现数组扁平化

function flatten(arr) {
  let res = [];

  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(flatten(arr[i]));
    } else {
      res.push(arr[i]);
    }
  }

  return res;
}

3. 字符串反转

String.prototype._reverse = function(a) {
	return a.split("").reverse().join("");
}

4. 将数组千分位用逗号隔开

function format(n) {
  let str = n.toString();
  let left = str.split('.')[0].split('');
  let right = str.split('.')[1].split('');

  for (let i = left.length - 3; i > 0; i -= 3) {
    left[i] = ',' + left[i];
  }

  for (let i = right.length - 3; i > 0; i -= 3) {
    right[i] = ',' + right[i];
  }

  return left.join('') + '.' + right.join('')
}
console.log(format(999999.9999));

5. 大数相加

function addBigNum(num1, num2) {
  const arr1 = num1.toString().split('').map(Number).reverse();
  const arr2 = num2.toString().split('').map(Number).reverse();

  const res = [];
  let carry = 0;

  const maxLen = Math.max(arr1.length, arr2.length);

  for (let i = 0; i < maxLen; i++) {
    const d1 = arr1[i] || 0;
    const d2 = arr2[i] || 0;

    const sum = d1 + d2 + carry;

    res.push(sum % 10);
    carry = Math.floor(sum / 10);
  }

  if (carry > 0) {
    res.push(carry);
  }

  return res.reverse().join('');
}

console.log(addBigNum(900000000000, 3000400));

6. 大数相乘

function mulBigNum(num1, num2) {
  const arr1 = num1.toString().split('').map(Number).reverse();
  const arr2 = num2.toString().split('').map(Number).reverse();

  const res = Array(arr1.length + arr2.length).fill(0);

  for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      res[i + j] += arr1[i] * arr2[j];

      if (res[i + j] >= 10) {
        res[i + j] %= 10;
        res[i + j + 1] += Math.floor(res[i + j] / 10);
      }
    }
  }

  while (res.length > 1 && res[res.length - 1] === 0) {
    res.pop();
  }

  return res.reverse().join('');
}

console.log(mulBigNum(444, 3000400));

7. 将js对象转化为树形对象

function jsonToTree(data) {
  let res = [];
  let map = {};

  data.forEach(item => map[item.id] = item);
  data.forEach(item => {
    let parent = map[item.pid];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      res.push(item);
    }
  })

  return res;
}

8. 将手机号变为四位*

let tel = 13233269513;
tel = tel.toString();
let arr = tel.split('');
arr.splice(3, 4, "****");
console.log(arr.join(''));

你可能感兴趣的:(面试题,前端,javascript,开发语言)