How can I slice an object in Javascript?(如何在 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 中对对象进行切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Javascript 中对对象进行切片?
基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
