区分数组与对象

1.实例继承原型对象的属性和方法

[].constructor.name    -    "Array"

2. instanceof 方法判断对象原型链上是否存在某个构造函数

[]  instanceof Array    -   true

3. toString  对对象的处理   (

推荐,不存在跨域问题

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var xArray = window.frames[window.frames.length - 1].Array;
var arr = new xArray(1, 2, 3);
console.log(arr instanceof Array); // false
console.log(arr.constructor === Array); // false
console.log(Object.prototype.toString.call(arr)==='[object Array]'); // true

)

Object.prototype.toString.call([])         -    "[object Array]"

 

扩展: in hasOwnProperty 之间区别

in操作符只要通过对象能访问到属性就返回true。 (遍历对象直系属性上无实际意义)

hasOwnProperty()只在属性存在于实例中时才返回true。

 

扩展:

Array.isArray

顾名思义,Array.isArray用来判断一个变量是否数组类型。JS的弱类型机制导致判断变量类型是初级前端开发者面试时的必考题,一般我都会将其作为考察候选人第一题,然后基于此展开。在ES6提供该方法之前,ES5至少有如下5种方式判断一个值是否数组:

var a = [];
// 1.基于instanceof
a instanceof Array;
// 2.基于constructor
a.constructor === Array;
// 3.基于Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf(a);
// 4.基于getPrototypeOf
Object.getPrototypeOf(a) === Array.prototype;
// 5.基于Object.prototype.toString
Object.prototype.toString.apply(a) === '[object Array]';

以上,除了Object.prototype.toString外,其它方法都不能正确判断变量的类型。

要知道,代码的运行环境十分复杂,一个变量可能使用浑身解数去迷惑它的创造者。且看:

var a = {
  __proto__: Array.prototype
};
// 分别在控制台试运行以下代码
// 1.基于instanceof
a instanceof Array; // true
// 2.基于constructor
a.constructor === Array; // true
// 3.基于Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf(a); // true
// 4.基于getPrototypeOf
Object.getPrototypeOf(a) === Array.prototype; // true

以上,4种方法将全部返回true,为什么呢?我们只是手动指定了某个对象的__proto__属性为Array.prototype,便导致了该对象继承了Array对象,这种毫不负责任的继承方式,使得基于继承的判断方案瞬间土崩瓦解。

不仅如此,我们还知道,Array是堆数据,变量指向的只是它的引用地址,因此每个页面的Array对象引用的地址都是不一样的。iframe中声明的数组,它的构造函数是iframe中的Array对象。如果在iframe声明了一个数组x,将其赋值给父页面的变量y,那么在父页面使用y instanceof Array ,结果一定是false的。 而最后一种返回的是字符串,不会存在引用问题。实际上,多页面或系统之间的交互只有字符串能够畅行无阻。

posted @ 2018-10-19 09:58  justSmile2  阅读(266)  评论(0编辑  收藏  举报