如何在 Javascript 中对对象进行切片?

2022-01-21 00:00:00 arrays slice object arguments javascript

我试图使用 Array.prototype 对对象进行切片,但它返回一个空数组,除了传递参数之外还有什么方法可以切片对象,还是只是我的代码有问题?谢谢!!

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

推荐答案

我试图使用 Array.prototype 对对象进行切片,但它返回一个空数组

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

那是因为它没有 .length 属性.它将尝试访问它,获取 undefined,将其转换为数字,获取 0,并从对象中切出最多那么多属性.为了达到预期的结果,您必须为它分配一个 length,或者手动通过对象的迭代器:

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

相关文章