Issue
Given a non whole number, or floating-point number (e.g. 3.5
), what happens when using that number as an index?
When using a floating-point number to access an index of an array or string, undefined
is returned.
'hello'[3.5]; // => undefined
When using floating-point numbers as indices passed to Array.prototype.slice()
or String.prototype.slice()
it seems the number is rounded down or the decimal is ignored.
['a','b','c','d','e'].slice(3.5, 4.5); // => ['d']
'hello'.slice(0.5, 1.5); // => 'h'
Why the different behavior, and what is actually happening here?
Solution
.slice
internally rounds its arguments to integers.
String.prototype.slice ( start, end )
- Let O be ? RequireObjectCoercible(this value).
- Let S be ? ToString(O).
- Let len be the length of S.
- Let intStart be ? ToIntegerOrInfinity(start).
- If intStart is -∞, let from be 0.
- Else if intStart < 0, let from be max(len + intStart, 0).
- Else, let from be min(intStart, len).
- If end is undefined, let intEnd be len; else let intEnd be ? ToIntegerOrInfinity(end).
- ...
where ToIntegerOrInfinity
does
- Let integer be floor(abs(ℝ(number))).
In contrast, when you do
'hello'[3.5];
no such rounding occurs.
Answered By - CertainPerformance Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.