<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb18030">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
function arraysSimilar(arr1, arr2){
if(arr1.length==arr2.length){
var m=0;
for(var i=0;i<arr1.length;i++){
for(j=m;j<arr2.length;j++){
if(Object.prototype.toString.apply(arr1[i])==Object.prototype.toString.apply(arr2[j])){
var t=arr2[m];
arr2[m]=arr2[j];
arr2[j]=t;
m++;
break;
}
else{
}
}
}
if(m==arr1.length){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
</script>
<script src="testData.js"></script>
</body>
</html>
首先你需要先用 Object.prototype.toString.call(arr1) === '[object Array]' 来判断是否是数组;
如下:
function arraysSimilar(arr1, arr2) { var num = 0; if (Object.prototype.toString.call(arr1) === '[object Array]' && Object.prototype.toString.call(arr2) === '[object Array]') { if (arr1.length === arr2.length) { for (var i = 0; i < arr1.length; i++) { for (var j = 0; j < arr2.length; j++) { if (Object.prototype.toString.call(arr1[i]) === Object.prototype.toString.call(arr2[j])) { num++; } } } if (num === arr1.length) { return true; } } } return false }
原来测试条件里并非都是数组,不能对基本类型使用length方法