简体   繁体   English

对象(具有属性)的转换数组返回0长度

[英]Converted Array from Object (with properties) returns 0 length

I have this code in my javascript file: 我的javascript文件中包含以下代码:

var items = {
    first: 'Item 1',
    second: 'Item 2',
    third: 'Item 3'
};
var arr = Array.prototype.slice.call(items);

console.log(arr.length);

I want to convert an object into an array. 我想将一个对象转换为数组。 My question is, when the object was converted into array, why does javascript return 0 when the object already has properties? 我的问题是,当对象转换为数组时,为什么当对象已经具有属性时javascript返回0 I hope someone could help me and if anyone wouldn't mind, I want it to be corrected without using jQuery. 我希望有人可以帮助我,如果有人不介意,我希望不使用jQuery就可以对其进行纠正。

You can use Object.entries() to create an array of arrays of properties, values from original object or an array of objects reflecting properties, values of original object. 您可以使用Object.entries()创建属性数组,原始对象的值的数组或反映属性,原始对象的值的对象的数组。

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). Object.entries()方法返回给定对象自己的可枚举属性[key, value]对的数组,其顺序与for...in循环所提供的顺序相同(区别在于for-in循环枚举原型链中的属性)。

 var items = { first: 'Item 1', second: 'Item 2', third: 'Item 3' }; var arr = Object.entries(items); console.log(arr); var arr1 = Object.entries(items) .map((value, index) => { return {[value.shift()]: value.pop()} }); console.log(arr1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM