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 中对对象进行切片?


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01