本文介绍了在console.log中显示对象属性的原始顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要进行一些调试才能看到一个JavaScript对象属性的原始顺序,但是(至少在chrome devtools中) console.log()
向我显示按字母顺序排列的对象。
I need for some debugging to see the original order of one JavaScript object's properties but (at least in chrome devtools) console.log()
shows me an alphabetically ordered object.
例如:
var obj = {
z: 1,
t: 2,
y: 3,
a: 4,
n: 5,
k: 6
}
console.log(obj)
显示:
Object {z: 1, t: 2, y: 3, a: 4, n: 5…}
a:4
k:6
n:5
t:2
y:3
z:1
//expected (needed ) original order
z: 1
t: 2
y: 3
a: 4
n: 5
k: 6
推荐答案
console.log
确实对属性进行排序,在某些情况下你可以使用 JSON.stringify
保留订单,例如
console.log
does indeed sort the properties, in some cases you can use JSON.stringify
which preserves the order, e.g.
console.log(JSON.stringify(obj, null /*replacer function */, 4 /* space */))
注意:与普遍看法相反,js对象按照(首先是整数,然后是插入顺序中的其他属性)
NB: contrary to the popular belief, js objects maintain the enumeration order, as per the OwnPropertyKeys specification (integers first, then other properties in insertion order)
这篇关于在console.log中显示对象属性的原始顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!