How can I slice an object in Javascript?

前端 未结 10 2206
青春惊慌失措
青春惊慌失措 2020-12-29 03:05

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

10条回答
  •  天命终不由人
    2020-12-29 03:56

    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);
    

提交回复
热议问题