如何在javascript中反转对象? [英] How to reverse an object in javascript?
问题描述
我想在JavaScript中反转一个对象。
例如:
I want to reverse an object in JavaScript. For Example:
输入: obj = {1:'banana',2:'apple',3:'orange' }
输出: ['orange','apple','banana']
我尝试使用'Array.prototype.reverse.apply(obj)',但无法获得结果。
I have tried with 'Array.prototype.reverse.apply(obj)', but not able to get the result.
var obj ={1: 'banana', 2: 'apple',3:'orange' };
var res =Array.prototype.reverse.apply(obj);
console.log(res); // return the same object, not reverse
Array.prototype.reverse的其他用法是什么( )?
What are the other usages of Array.prototype.reverse()?
推荐答案
您可以先将几乎类似数组的对象转换为真实数组,然后使用 .reverse()
:
You can first convert your almost-array-like object to a real array, and then use .reverse()
:
Object.assign([], {1:'banana', 2:'apple', 3:'orange'}).reverse();
// [ "orange", "apple", "banana", <1 empty slot> ]
如果因为您的第一个索引是 1,那么结尾处的空槽
而不是 0
。您可以使用 .length -
或 .pop()
删除空插槽。
The empty slot at the end if cause because your first index is 1
instead of 0
. You can remove the empty slot with .length--
or .pop()
.
或者,如果你想借用 .reverse
并在同一个对象上调用它,它必须是一个类似于完全数组的对象。也就是说,它需要长度
属性:
Alternatively, if you want to borrow .reverse
and call it on the same object, it must be a fully-array-like object. That is, it needs a length
property:
Array.prototype.reverse.call({1:'banana', 2:'apple', 3:'orange', length:4});
// {0:"orange", 1:"apple", 3:"banana", length:4}
注意它将返回相同的类似于全数组的对象,因此它不是真正的数组。然后,您可以使用 delete
删除长度
属性。
Note it will return the same fully-array-like object object, so it won't be a real array. You can then use delete
to remove the length
property.
这篇关于如何在javascript中反转对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!