PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 11, 2022

[FIXED] What happens when using a non-whole number as an index in JavaScript?

 December 11, 2022     arrays, javascript, string, syntax     No comments   

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 )

  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.



Answered By - CertainPerformance
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing