js的数组和对象的多种"复制"和"清空", 以及区分JS数组和对象的方法
栏目: JavaScript · 发布时间: 5年前
内容简介:1.数组清空的方法2.数组复制方法1.判断对象是否为空
一.数组清空与复制方法
1.数组清空的方法
var a = [1,2,3]; a.length = 0; //方法1 a.splice(0, a.length); //方法2
2.数组复制方法
var a = [1,2,3]; a.slice(0)
二.对象清空与复制方法
1.判断对象是否为空
Object.key.length==0 //为空 ES6
2.对象复制
(1)万能办法
function clone(obj){ let temp = null; if(obj instanceof Array){ temp = obj.concat(); }else if(obj instanceof Function){ //函数是共享的是无所谓的,js也没有什么办法可以在定义后再修改函数内容 temp = obj; }else{ temp = new Object(); for(let item in obj){ let val = obj[item]; temp[item] = typeof val == 'object'?clone(val):val; //这里也没有判断是否为函数,因为对于函数,我们将它和一般值一样处理 } } return temp; }
(2)JSON对象序列化方法, 弊端: 不能复制函数
JSON.parse(JSON.stringify(obj))
三.判断是否为数组和对象的方法
1.toString方法
Object.prototype.toString.call(array) === '[object Array]' //true Object.prototype.toString.call(obj) === '[Object Object]' //true
2.constructor方法
obj.constructor === Array//true obj.constructor === Object //true
3.instanceof方法, 弊端: 区分不开对象或者数组
obj instaceof Object //true array instaceof Object// true
4.isArray方法
Array.isArray([1,2,3]) //true
以上是我认为无懈可击的方法, 其他还有很多, 需要请留言
想了解原生js的"数组"和"对象"的方法, 请点击 JavaScript教程-阮一峰
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- mongodb如何实现数组对象求和
- ES的解构赋值-数组&对象
- 数组对象根据对象中指定的属性去重?你知道多少
- 后台接收Json请求参数兼容数组和单个对象
- vue改变对象或数组时的刷新机制总结
- 记一次踩坑|空table应该编码为数组还是对象
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Automate This
Christopher Steiner / Portfolio / 2013-8-9 / USD 25.95
"The rousing story of the last gasp of human agency and how today's best and brightest minds are endeavoring to put an end to it." It used to be that to diagnose an illness, interpret legal docume......一起来看看 《Automate This》 这本书的介绍吧!