I would like to make a function like this work as intended in JavaScript:
function isLastElem(array, elem) {
if (elem === array[array.length-1]) {
return true;
}
else {
return false;
}
}
The intention is that the function should be able to identify the last element of any array. For example:
let arr = [0, 1, 2];
console.log(isLastElem(arr, 2)); // I would expect false to be returned
console.log(isLastElem(arr, arr[2])); // I would expect true to be returned
However, since numbers are primitive values, they are passed to the function by their values and thus both function calls return true. Any way to solve this and pass numbers by reference?
The important idea here would be to make it usable in a for each cycle. For example:
let arr = [0, 1, 0];
arr.forEach((elem) => {
if (isLastElem(arr, elem)) {
console.log("Found the last element!");
}
});
At the first 0 the function should return false, since that is not the last element of the array. Then at the second 0 it should return true and log the message.
===to 2. All number values that are 2 are indistinguishable.arrand2. (It would make a better example to discuss if the array elements were not equal to the indices).