Home > front end >  What happens when using a non-whole number as an index in JavaScript?
What happens when using a non-whole number as an index in JavaScript?

Time:10-14

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?

CodePudding user response:

.slice internally rounds its arguments to integers.

String.prototype.slice ( start, end )

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let len be the length of S.
  4. Let intStart be ? ToIntegerOrInfinity(start).
  5. If intStart is -∞, let from be 0.
  6. Else if intStart < 0, let from be max(len intStart, 0).
  7. Else, let from be min(intStart, len).
  8. If end is undefined, let intEnd be len; else let intEnd be ? ToIntegerOrInfinity(end).
  9. ...

where ToIntegerOrInfinity does

  1. Let integer be floor(abs(ℝ(number))).

In contrast, when you do

'hello'[3.5];

no such rounding occurs.

  • Related