Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

javascript - can I prevent automatic sort of JS Object numeric property?

Given the following JS Object

var stk={3:{221:1,220:1,224:1,226:1,198:1},24:{221:1,220:1,224:1,226:1,198:1},33:{198:1},9:{223:1,221:1,220:1,224:1,226:1,198:1},156:{220:1,224:1,226:1}};

console.log(stk[24]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

can I prevent automatic sort of JS Object numeric property?

You can't. But you shouldn't be paying attention to or caring about the order of properties in JavaScript objects anyway. While they have an order (now), it's best to act as though they're unordered. If you want a specific order, use an array (which is also an object, and that's part of why property names that are integer indexes are visited in numeric order).

The problem here is that the I have no control over the construction of var stk; because it is built inside a PHP code from a third party plugin.

If that's the case, you can't do anything about it. If you could get the PHP to output it as a string, e.g.:

var stk = "{3:{221:1,220:1,224:1,226:1,198:1},24:{221:1,220:1,224:1,226:1,198:1},33:{198:1},9:{223:1,221:1,220:1,224:1,226:1,198:1},156:{220:1,224:1,226:1}}";

...then you could parse it yourself and maintain order. But if you can't even do that, there's nothing you can do about it.

You might be able to bend over backward and find it in the text of the JavaScript, if it's an inline script tag rather than a .js file (if it's a .js file, your ability to read it will depend on whether it's from the same origin as your page).

For example:

var text = $("#from-plugin").text();
var match = /var stk=({.*};)/.exec(text);
console.log(match ? match[1] : "Couldn't find it");
<script id="from-plugin">
// other stuff
var stk={3:{221:1,220:1,224:1,226:1,198:1},24:{221:1,220:1,224:1,226:1,198:1},33:{198:1},9:{223:1,221:1,220:1,224:1,226:1,198:1},156:{220:1,224:1,226:1}};
// other stuff
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...