Saturday, April 26, 2014

Slicing in javascript

Slicing in javascript
Click to toggle code (may have to try twice)
// an object with the length property
var my_object = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    length: 5
};
// convert it to an Array object and slice elements out of it.
var sliced = Array.prototype.slice.call( my_object, 3 );
undefined
sliced                                                          // Array [ "three", "four" ]
var sliced = Array.prototype.slice.call( my_object, 0, 3 );     // undefined
sliced                                                          // Array [ "zero", "one", "two" ]
my_object                                                       // Object { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", length: 5 }

0 comments: