I'm trying to chain methods of an Array
object together but it won't let me.
var arr = [1,2,3];
arr.splice(-3, 1, 'foot').splice(arr.length,0, 'hand');
console.log(arr) // ['foot', 2, 3]
//trying to get ['foot', 2, 3, 'hand']
This doesn't work. I have to split up the second splice
onto a new statement. Why doesn't this work? I've seen chaining done many times in JavaScript code.
Simply because Array.prototype.splice
returns an array containing the deleted elements, as you can find on its documentation page.
So basically some methods allow chaining and some dont. If that is the first time you use them, you can refer to the doc.
To be more precise, most methods of an Array create a new Array (at the exception of splice), so it's not technically a chaining since you don't apply different methods on the same instance of the same array. Typical cloning-chaining methods are filter
, map
, find
.