Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  17] [ 5]  / answers: 1 / hits: 98321  / 8 Years ago, mon, september 5, 2016, 12:00:00

I was trying to slice an object using Array.prototype, but it returns an empty array, is there any method to slice objects besides passing arguments or is just my code that has something wrong? Thx!!



var my_object = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four'
};

var sliced = Array.prototype.slice.call(my_object, 4);
console.log(sliced);

More From » arrays

 Answers
14

I was trying to slice an object using Array.prototype, but it returns an empty array



That's because it doesn't have a .length property. It will try to access it, get undefined, cast it to a number, get 0, and slice at most that many properties out of the object. To achieve the desired result, you therefore have to assign it a length, or iterator through the object manually:




var my_object = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four'};

my_object.length = 5;
console.log(Array.prototype.slice.call(my_object, 4));

var sliced = [];
for (var i=0; i<4; i++)
sliced[i] = my_object[i];
console.log(sliced);




[#60802] Friday, September 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jerome

Total Points: 592
Total Questions: 98
Total Answers: 101

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
jerome questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Fri, Oct 22, 21, 00:00, 3 Years ago
Sat, Sep 19, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
;