Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE <= 8 .splice() not working

Tags:

javascript

I have some simple code you can see in my fiddle. It alerts properly in all browsers and IE9, but not IE8 or 7.

var func = function( x ) {
    var slice = [].slice,
        args = slice.call( arguments ),
        pass = args.splice(1);

    alert( pass );

};

func( 'a', 1, 2 );

EDIT Using the solution I posted what I used here: http://jsfiddle.net/7kXxX/4/

I am using this in a case where I don't know how many arguments are coming, which is why I'm using "arguments"

like image 704
Dave Stein Avatar asked Nov 30 '11 21:11

Dave Stein


People also ask

What is the function of splice () in JavaScript?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

What is difference between Slice & Splice?

Slice is used to get a new array from the original array whereas the splice is used to add/remove items in the original array. The changes are not reflected in the original array in the case of slice and in the splice, the changes are reflected in the original array.

What is the alternative of splice in JavaScript?

Alternative of Array splice() method in JavaScript If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends.

Is JavaScript splice destructive?

The . splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).


1 Answers

The ECMAScript 3rd edition standard requires the second deleteCount argument:

Array.prototype.splice(start, deleteCount [, item1 [, item2[,...]]])

MSDN docs show that IE follows this standard:

arrayObj.splice(start, deleteCount, [item1[, item2[, . . . [,itemN]]]])

Firefox's SpiderMonkey allows the second argument to be optional (as do other modern browsers):

array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index[, howMany[, element1[, ...[, elementN]]]])

Description:

howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.

Sources:

  • http://bclary.com/2004/11/07/#a-15.4.4.12
  • http://msdn.microsoft.com/en-us/library/wctc5k7s%28v=VS.85%29.aspx
  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
like image 116
Wayne Avatar answered Oct 05 '22 15:10

Wayne