js判断是否为数组,对象转数组方法

注意:不能使用typeof来判断是否为数组,因为它返回的是一个对象

typeof操作符
// 数值
typeof 37 === 'number';
 
// 字符串
typeof '' === 'string';
 
// 布尔值
typeof true === 'boolean';
 
// Symbols
typeof Symbol() === 'symbol';
 
// Undefined
typeof undefined === 'undefined';
 
// 对象
typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
 
// 下面的例子令人迷惑,非常危险,没有用处。避免使用它们。
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
 
// 函数
typeof function() {} === 'function';

从上面的实例我们可以看出,利用typeof除了array和null判断为object外,其他的都可以正常判断。

使用instanceof操作符 和 对象的constructor 属性
var arr = [1,2,3,1];
console.log(arr instanceof Array); // true
 
var fun = function(){};
console.log(fun instanceof Function); // true
var arr = [1,2,3,1];
console.log(arr.constructor === Array); // true
 
var fun = function(){};
console.log(arr.constructor === Function); // true
使用 Object.prototype.toString 来判断是否是数组
Object.prototype.toString.call( [] ) === '[object Array]'  // true
 
Object.prototype.toString.call( function(){} ) === '[object Function]'  // true
使用 原型链 来完成判断
[].__proto__ === Array.prototype  // true
 
var fun = function(){}
fun.__proto__ === Function.prototype  // true
使用Array.isArray()
Array.isArray([])   // true

ECMAScript5将Array.isArray()正式引入JavaScript,目的就是准确地检测一个值是否为数组。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都实现了这个方法。但是在IE8之前的版本是不支持的。

Array.isArray()这个方法的执行速度比原型链的方式快了近一倍。

将对象转为数组
var obj = {
   a: 'xx',
   b: 'yy',
   c: 'zz'
 }
 var arr = []
  for (let i in obj) {
    let o = {};
    o[i] = obj[i];
    arr.push(o)
  }
  console.log(arr); 
   // 打印结果:
 	[
	   	{a: 'xx'},
	   	{b: 'yy'},
	   	{c: 'zz'}
    ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值