Why in this code the last element of the array passed to the function inArray ([1,2,3,4,5]) is not added to the result array? But if you add any other element to the end of the array, the result will be correct (result = [3,4,5]).

function inArray(array) { return function (currentArray) { var result = []; for (var i = 0; i < currentArray.length; ++i) { if (currentArray[i] in array ) result.push(currentArray[i]); } return result ; } } var a = inArray([1,2,3,4,5])([3,5,4]); // result = 3,4 alert(a); 
  • one
    Igor essentially answered, but in general, you were just “lucky” that you took small numbers, answering the second part of the question: you partially worked everything only because there are elements in the array [1,2,3,4,5] with indices 3, 4, hence the absence of 5 (since the last index is 4). - MedvedevDev

1 answer 1

Because you mixed up the in operator and the function indexOf/includes .

But if you add to the end of the array ...

(There are two arrays in the code. Which one is it? Obviously, the first one.)

Because then an element with index 5 appears in the array .

 function inArray(array) { return function (currentArray) { var result = []; for (var i = 0; i < currentArray.length; ++i) { if (array.includes(currentArray[i])) result.push(currentArray[i]); } return result ; } } var a = inArray([1,2,3,4,5])([3,5,4]); // result = 3,4 console.log(a);