array.slice() question

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

Is array.slice() guaranteed to return a zero-length array if the first
argument is greater than the length of the array? Or is it allowed to
throw an exception?
 
M

Michael Winter

Is array.slice() guaranteed to return a zero-length array if the
first argument is greater than the length of the array?

In a conforming implementation of ECMA-262, yes. I can't say that I've
ever called it with out-of-bounds arguments, though.
Or is it allowed to throw an exception?

Built-in methods only throw exceptions in very specific and
unrecoverable circumstances. For instance, a syntax error in an eval
call, or a RegExp or Function constructor call, or applying non-generic
prototyped methods (like valueOf) to instances of different objects.
Arguments are usually normalized to values that make sense, especially
those that can be bounded to range.

Mike
 
C

Christopher Benson-Manica

Michael Winter said:
In a conforming implementation of ECMA-262, yes. I can't say that I've
ever called it with out-of-bounds arguments, though.

I'm creating a copy of an array with one item removed, like so:

var copyWithItemRemoved=someArray.slice( 0, idx ).concat( someArray.slice(idx+1) );

Am I missing a better way to do this? (See my next post, I will ask
in a new topic.)
 
E

Evertjan.

Christopher Benson-Manica wrote on 06 dec 2005 in comp.lang.javascript:
I'm creating a copy of an array with one item removed, like so:

var copyWithItemRemoved=someArray.slice( 0, idx ).concat(
someArray.slice(idx+1) );

Am I missing a better way to do this? (See my next post, I will ask
in a new topic.)

var theRemevedItem = someArray.splice(idx, 1)
var copyWithItemRemoved = someArray
 
C

Christopher Benson-Manica

Evertjan. said:
var theRemevedItem = someArray.splice(idx, 1)
var copyWithItemRemoved = someArray

That isn't what I want, though - splice also modifies the original
array, which I am explicitly trying to avoid. I could, of course, do

var copyWithItemRemoved=someArray.slice( 0 );
copyWithItemRemoved.splice( idx, 1 );

but I'm not enthusiastic.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top