#javascript
При таком коде функция возвращает true: function areArraysSame(array1, array2) { if (array1.length !== array2.length) { return; } for (var i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) { return false; } else { return true; } } } alert(areArraysSame([1, 2, 3], [1, 2, 2]));
Ответы
Ответ 1
Нельзя возвращать true внутри цикла, пока еще есть непроверенные элементы массивов. function areArraysSame(array1, array2) { if (array1.length !== array2.length) { return false; } for (var i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) { return false; } } return true; } console.log(areArraysSame([1, 2, 3, 4], [1, 2, 2, 4])); console.log(areArraysSame([1, 2, 3, 4], [1, 2, 3, 4])); console.log(areArraysSame([1, 2, 3, 4], [1, 2, "3", 4]));Ответ 2
многоуровневое сравнение массивов и объектов var equals = function(arr1, arr2) { var req = false; switch (arr1.constructor) { case Object: req = true; for (var name in arr1) { if (name in arr2) { if (arr1[name] === undefined || arr2[name] === undefined) if (arr1[name] === arr2[name]) continue; else { req = false; break; } if (arr1[name].constructor !== arr2[name].constructor) { req = false; break; } if ([Array, Object, NodeList, HTMLCollection].indexOf(arr1[name].constructor) !== -1) { if (!equals(arr1[name], arr2[name])) { req = false; break; } else continue; } if (arr1[name] !== arr2[name]) { req = false; break; } } else { req = false; break; } } break; case Array: case NodeList: case HTMLCollection: if (arr1.length === arr2.length) { req = true; for (var i = 0, len = arr1.length; i < len && req === true; i++) { if (arr1[i] === undefined || arr2[i] === undefined) if (arr1[i] === arr2[i]) continue; else { req = false; break; } if (arr1[i].constructor !== arr2[i].constructor) req = false; if ([Array, Object, NodeList, HTMLCollection].indexOf(arr1[i].constructor) !== -1) { if (!equals(arr1[i], arr2[i])) req = false; else continue; } if (arr1[i] !== arr2[i]) req = false; } } break; } return req; }; console.log(equals( [1, {s: 1},[1, "a", {gg: "vp"}]], [1, {s: 1},[1, "a", {gg: "vp"}]] )); console.log(equals( [1, {s: 1},[1, "a", {gg: "vp"}]], [1, {s: 1},[1, "a", {gg: 1}]] ));
Комментариев нет:
Отправить комментарий