Task Please write the arraysSimilar function in the index.html file to determine whether the two incoming arrays are similar. specific requirement: The members in the array are of the same type, but the order can be different. For example, [1, true] is similar to [false, 2]. The array lengths are consistent. The type judgment range needs to be distinguished: String, Boolean, Number, undefined, null, function, date, window. When all the above are satisfied, "Judgment Result: Pass" is returned, otherwise "Judgment Result: Fail" is returned.
This is a strange requirement, mainly requiring a "similar" judgment.
The first instinct is to sort the array directly and then compare the types. But due to the size comparison characteristics of JS, this is wrong.
Then we need to change it. Here I take the abbreviation of the type name of each element, so that we can approximate \(O(NlogN)\) and then use it as the typo of the entire array. You can approximate \(O(N)\) to compare whether the arrays are similar.
The second point to note is the judgment of invalid parameters. At first, == null
was used to judge null
and undefined
, but The parameter type is required to be an array, so use instanceof
to judge.
The alternative to getting the type is to use Object.prototype.toString()
, which can accurately get the class name of the object on the prototype chain, but the function may be overridden, so it is not preferred.
/* * param1 Array * param2 Array * return true or false */function arraysSimilar(arr1, arr2) { // 获取单个元素的类型名简写,已经满足需求 // 替代方案:考虑用Object.prototype.toString,但会被hack function getTypeNameS(item) { if (item === null)return 'nl'; else if (item instanceof Date) return 'd'; else if (item instanceof Window) return 'w'; elsereturn (typeof item)[0]; } // 获取整个数组排序后的typo function getArrayTypo(arr) { return arr.map(function (item) { return getTypeNameS(item); }).sort().join(''); } // 可以判断==null,但由于要求类型为数组,那就用instanceof if (!(arr1 instanceof Array) || !(arr2 instanceof Array)) return false; // 长度不等的情况,可以合并到typo比较中 if (arr1.length != arr2.length)return false; // 对于typo使用内置的字符串比较 return getArrayTypo(arr1) == getArrayTypo(arr2); }
This article is released under the Creative Commons License Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. You are welcome to quote, reprint or derive it, but you must retain the attribution BlackStorm and the link to this article, and Cannot be used for commercial purposes without permission. If you have any questions or authorization negotiations, please contact me.
The above is the detailed content of An arraySimilar function on imooc's 'JavaScript in a Simple Language'. For more information, please follow other related articles on the PHP Chinese website!