拾叁叁
2017-10-24 15:45

问题如题目,是什么原因呢??求大神帮帮忙~~
for循环里面的i、j不加var关键字,则为全局变量,到case2时这个i==case1.arr1.length
思路是判断两个数组中每种类型的元素个数相同则判断数组相似
function arraysSimilar(x, y) {
// 判断是否都是数组
if (!x instanceof Array || !y instanceof Array) {
return false;
}
// 判断数组长度是否一致
if (x.length != y.length) {
return false;
}
// 获取数组元素的具体类型 , 按要求分类
// 如果每种类型的元素个数相同则判断数组相似
types_of_x = getTypes(x);
types_of_y = getTypes(y);
// console.log(getTypes(x))
// 对这两个数组的类型进行比较, 如果某个类型的元素个数不同则直接false
result = true
for(k in types_of_x) {
if(types_of_x[k] != types_of_y[k]){
result = false ;
// console.log( k + " elements count not equal");
break;
}
}
return result;
}
function getTypes(target) {
types_of_target = {
"number": 0,
"string": 0,
"boolean": 0,
"undefined": 0,
"function": 0,
"null": 0,
"date": 0,
"array": 0,
"other": 0,
}
//target 是数组, 直接用map遍历
//typeof 返回的是基本数据类型(string, boolean ,number,undefined,) + function + object
//object 需要单独拿出来,除object需要进一步instanceof外 , 其他都只需要typeof即可
target.map(function (element) {
//对象类型
if (typeof(element) == "object") {
// 对基本类型 null 进行单独处理, 因为typeof(null) 的输出是object
if (element == null) {
return types_of_target['null']++;
}
//判断对象类型的, 具体类别
if( element instanceof Date) {
return types_of_target["date"] ++ ;
}
//数组类型
if( element instanceof Array ) {
return types_of_target["array"] ++;
}
//如果不是以上类型 , 则是其他对象类型
return types_of_target["others"] ++;
} else
{
//除对象类型外 , 基本类型(除null外), 还有function 类型, 直接赋值
type = typeof (element)
// console.log("element " + element + " type is "+ type)
if (!types_of_target[type]) {
types_of_target[type] = 1;
} else {
types_of_target[type]++;
}
}
})
return types_of_target;
}
arr_1 = [1, true, new Date(), undefined, function fun() {
}, [1, 2, 3], false, "yes"];
arr_2 = [false, 2, "no", 45, 67, 89, true, 1]
arr_3 = [false, 20, "yes", 45, 67, 79, 1,false]
console.log(arraysSimilar(arr_2, arr_3));
console.log(arraysSimilar(arr_1, arr_3));
哪里有case呀。。
JavaScript深入浅出
281088 学习 · 1054 问题
相似问题