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

查看:35
本文介绍了如何在 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天全站免登陆