js中数组的处理

js中数组的处理

一.查询数组中是否存在某一元素

let arr = ['a', 'b', 'c', 'd', NaN, undefind];
// 1.使用indexOf
	arr.indexOf('b'); // 1
	arr.indexOf(NaN); // -1 无法精准判断
	arr.indexOf(undefind); // -1 无法精准判断

// 2.使用es6新属性includes(),此方法可以判断NaN,对比es5中的indexOf,
	此方法返回的是true或false,结果也更利于做判断
	site.includes('b'); // true
	site.includes(NaN); // true
	arr.indexOf(undefind); // true

二.去两个数组的交集

let a = [1,2,3];
let b = [2];
const intersect = (nums1, nums2) => {
  const map = {}
  const res = []
  for (let n of nums1) {
    if (map[n]) {
      map[n]++
    } else {
      map[n] = 1
    }
  }
  for (let n of nums2) {
    if (map[n] > 0) {
      res.push(n)
      map[n]--
    }
  }
  return res
}

intersect(a, b);

三.判断是否是数组

1. Object.prototype.toString.call()
	继承Object对象的元素都有toString方法,通过此方法会返【object type】{(如果toString没有被改写),type就是元素的类型,除Object类型对象以外其他类型使用toString方法,会返回字符串,所以使用call,来改变toString方法的执行上下文
	const a = ['aaa'];
	a.toString();     // 'aaa'
	Object.prototype.toString.call(a);       // "[object Array]"

2. instanceof
 	instanceof  的内部机制是通过判断对象的原型链中是不是能找到类型的 prototype,找到就返回true,找不到就返回false,
 	const a = ['aaa'];
 	a instanceof Array;  // true
 	但 instanceof 只能用来判断对象类型,原始类型不可以。并且所有对象类型 instanceof Object 都是 true

3. Array.isArray()
	const a = ['aaa'];
	Array.isArray(a) //true

4.constructor
	const a = ['aaa'];
	a.constructor == Array    // true
	

你可能感兴趣的:(js中数组的处理)