I'm having trouble grasping the JavaScript example provided below.
function containsAll(arr) {
for (let k = 1; k < arguments.length; k++) {
let num = arguments[k];
if (arr.indexOf(num) === -1) {
return false;
}
}
return true;
}
let x = [2, 4, 6, 7];
console.log(containsAll(x, 2, 4, 7));
console.log(containsAll(x, 6, 4, 9));
When I run this code, it outputs 1
and 0
to the console.
I'm struggling to visualize how this function should operate.
- Considering the call console.log(containsAll(x, 2, 4, 7)), the
x
should be substituted, resulting in console.log(containsAll(2, 4, 6, 7, 2, 4, 7)). - The
function containsAll
processes those numbers (2, 4, 6, 7, 2, 4, 7). In the line,
,for(let k = 1; k < arguments.length; k++)
k
should represent a new array [1, 2, 3, 4, 5, 6], depending on the argument length which corresponds to the length of arr (in this instance, the length is 7), correct?Next, in
let num = arguments[k]; if (arr.indexOf(num) === -1) {return false;}
let num
should take the valuenum = 1
, is that right?Subsequently, the if statement checks if
1
is present in the array, arr = [2, 4, 6, 7, 2, 4, 7]. If no match is found, it returns false. This process should continue for each number in thearr
array, correct?
I'm simply trying to understand why the output is 1
for
console.log(containsAll(x, 2, 4, 7));
when I expected something like [false, true, false, true, false, true]
.