如何在Javascript中切片对象? [英] How can I slice an object in Javascript?

查看:307
本文介绍了如何在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);

这篇关于如何在Javascript中切片对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆