这个随笔其实是为了感谢清风笑给的一个提示,不仅仅是告诉我怎么判断数组,更让我有了认真读一读 《javascript权威指南》的想法。
比较和拷贝其实是一回事,代码如下:
比较和拷贝其实是一回事,代码如下:
//
//Compare object function
//
function Compare(fobj,sobj)
{
var ftype = typeof(fobj);
var stype = typeof(sobj);
if (ftype == stype)
{
if (ftype == "object")
{
if (fobj.constructor == Array && sobj.constructor == Array)//array
{
return CompareArray(fobj,sobj)
}
else if (fobj.constructor != Array && sobj.constructor != Array)//object
{
return CompareObject(fobj,sobj);
}
return false;
}
return fobj == sobj;
}
return false;
}
function CompareObject(fobj,sobj)
{
for (var ele in fobj)
{
if (sobj[ele] == undefined) return false;
if (!Compare(fobj[ele],sobj[ele]))
{
return false;
}
}
return true;
}
function CompareArray(farr,sarr)
{
if (farr.length != sarr.length)
{
return false;
}
for (var i = 0; i < farr.length; i++)
{
if (!Compare(farr[i],sarr[i]))
{
return false;
}
}
return true;
}
//Compare object function
//
function Compare(fobj,sobj)
{
var ftype = typeof(fobj);
var stype = typeof(sobj);
if (ftype == stype)
{
if (ftype == "object")
{
if (fobj.constructor == Array && sobj.constructor == Array)//array
{
return CompareArray(fobj,sobj)
}
else if (fobj.constructor != Array && sobj.constructor != Array)//object
{
return CompareObject(fobj,sobj);
}
return false;
}
return fobj == sobj;
}
return false;
}
function CompareObject(fobj,sobj)
{
for (var ele in fobj)
{
if (sobj[ele] == undefined) return false;
if (!Compare(fobj[ele],sobj[ele]))
{
return false;
}
}
return true;
}
function CompareArray(farr,sarr)
{
if (farr.length != sarr.length)
{
return false;
}
for (var i = 0; i < farr.length; i++)
{
if (!Compare(farr[i],sarr[i]))
{
return false;
}
}
return true;
}