我正在制作discord.js机器人,我想要make命令,该命令将写入5个具有最高平衡的用户。当我运行此代码
/**
* Instantiates an instance
*
* @since 6.3
* @access public
*
* @param array|string $args Array or query string of arguments
* @return object Instance object
*/
public function load_instance( $args = '' ) {
$args['instance'] = count( $this->loaded_instances );
$instance = new Theme_My_Login_Template( $args );
if ( $args['instance'] == $this->request_instance ) {
$instance->set_active();
$instance->set_option( 'default_action', $this->request_action );
}
$this->loaded_instances[] = $instance;
return $instance;
}
我得到了所有的琴弦...
let coins = require("./coins.json");
for (var key in coins) {
if (coins.hasOwnProperty(key)) {
console.log(key + ": " + coins[key].coins);
}
}
因此表示:298462251453775873: 2090
208120625947082752: 210
461643208422588446: 370
290099182310785025: 10
468737161563209738: 420
381182620513468417: 40
408908116101431298: 180...
。我该如何对这些值进行排序而不丢失哪个用户拥有它?
答案 0 :(得分:0)
因此将其转换为具有Object.keys或Object.entries的数组,然后对其进行排序。
const users = {
'1': 100,
'2': 200,
'3': 50
}
const sorted = Object.entries(users).sort((a, b) => a[1] > b[1] ? -1 : 1)
console.log(sorted)
const users = {
'1': 100,
'2': 200,
'3': 50
}
const sorted = Object.keys(users).sort((a, b) => users[a] > users[b] ? -1 : 1)
console.log(sorted)
sorted.forEach(k => {
console.log(k, users[k])
})
答案 1 :(得分:0)
使用<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
function doThisWhenLoaded(){
var code = document.getElementsByTagName("body");
code.append("<p>Yes it did.</p>");
}
</script>
</head>
<body onload="doThisWhenLoaded">
<h1 style="font-family:sans-serif;">Did it work?</h1>
</body>
</html>
和Object.keys()
,可以实现所需的功能。
array.slice()
答案 2 :(得分:0)
您可以像下面那样使用Object.entries
,Array.map
对对象进行排序
let coins = {
'298462251453775873': {coins: 2090}
, '208120625947082752': {coins: 210}
, '461643208422588446': {coins: 370}
, '290099182310785025': {coins: 10}
, '468737161563209738': {coins: 420}
, '381182620513468417': {coins: 40}
, '408908116101431298': {coins: 180}
}
coins = Object.assign(...Object.entries(coins)
.sort(([,a],[,b]) => a.coins - b.coins)
.map(([k,v]) => ({[k]: v})))
for (var key in coins) {
if (coins.hasOwnProperty(key)) {
console.log(key + ": " + coins[key].coins);
}
}
//console.log(coins)