1

I am trying to understand why test3 and test1 produce the same result, which is an array [1,2] but test2 produces an empty array. Isn't the Function property arguments returning an array like object? I expect all three test results to produce an array of [1,2].

/*eslint-disable no-console */
var testFunc = function(){
    console.log(arguments);
    console.log("test3: ", Array.prototype.slice.apply(arguments));
};

testFunc(1,2);
console.log("test1: ", Array.prototype.slice.apply([1,2]));
console.log("test2: ", Array.prototype.slice.apply({[0]:1, [1]:2}));

2 Answers 2

1

test2 doesn't produce the result you expect because you're calling it on a non-array-like object: it's missing length. test1 and test3 produce the result you expect because you're calling it on array-like objects. Since test2 is missing length, when slice reads length, it gets undefined, which gets converted to NaN, so 0 gets used as the length of the source array. (If you're curious, in the spec it's slice -> LengthOfArrayLike(obj) -> ToLength(obj.length) -> ToInteger(undefined) -> ToNumber(undefined); ToNumber returns NaN, which ToInteger converts to 0.)

If we add length to test2, it also produces what you expect:

/*eslint-disable no-console */
var testFunc = function(){
    console.log(arguments);
    console.log("test3: ", Array.prototype.slice.apply(arguments));
};

testFunc(1,2);
console.log("test1: ", Array.prototype.slice.apply([1,2]));
console.log("test2: ", Array.prototype.slice.apply({0:1, 1:2, length:2}));
.as-console-wrapper {
    max-height: 100% !important;
}


Side note: No need for computed property notation when building the array-like object for test2, numeric literals are valid property names in object literals (I've removed the computed notation in the snippet above).

Sign up to request clarification or add additional context in comments.

Comments

1

For an object to be array-like, it needs to have a .length property:

console.log("test2: ", Array.prototype.slice.apply({0:1, 1:2, length: 2}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.