【问题标题】:Sort() not working排序()不工作
【发布时间】:2018-05-21 21:43:07
【问题描述】:

我在排序来自 coinmarketcap api 的数据时遇到问题。使用 ajax api 调用,sort 可以返回具有正确排名的数组。使用 axios api 调用,如下所示,它没有。

这是我使用 axios 和 vue.js 的代码:

let coinMarket = 'https://api.coinmarketcap.com/v2/ticker/?limit=10'
let updateInterval = 60 * 1000;

let newApp = new Vue({
  el: '#coinApp',
  data: {
    // data within an array
    results: []
},
  methods: {
    getCoins: function() {
        axios
            .get(coinMarket)
            .then((resp) => {
              this.results = formatCoins(resp);
            });
    },

    getColor: (num) => {
        return num > 0 ? "color:green;" : "color:red;";
    },
},
    created: function() {
        this.getCoins();
    }
})
setInterval(() => {
        newApp.getCoins();
    },
    updateInterval
);
function formatCoins(res) {
    var coinDataArray = []
    Object.keys(res.data).forEach(function(key) {
        coinDataArray.push(res.data[key])
    })
    coinDataArray.sort(function(a,b) {
        return a.rank > b.rank
    })
    console.log(coinDataArray)
}

我哪里出错了?

【问题讨论】:

  • 升序排序的正确方法是a.rank - b.rank检查docs
  • 嗨,我试过了,但结果是一样的。
  • 您的数据是什么样的?确保您的 rank 值是数字
  • 排名数据为数字。我真的很摸不着头脑。
  • 能否请您发布您的coinDataArray 内容?

标签: sorting vue.js axios


【解决方案1】:

如果你查看https://api.coinmarketcap.com/v2/ticker/?limit=10回复的数据,你会发现你需要的数据在res.data.data下,而不是res.data下。

所以在函数=formatCoins 中,将res.data 替换为res.data.data,然后就可以了。

Vue.config.productionTip = false
let coinMarket = 'https://api.coinmarketcap.com/v2/ticker/?limit=10'
let updateInterval = 60 * 1000;

function formatCoins(res) {
    var coinDataArray = []
    Object.keys(res.data.data).forEach(function(key) {
      
        coinDataArray.push(res.data.data[key])
    })
    coinDataArray.sort(function(a,b) {
        return a.rank - b.rank
    })

    return coinDataArray
}

let newApp = new Vue({
  el: '#coinApp',
  data: {
    // data within an array
    results: []
  },
  methods: {
    getCoins: function() {
        axios
            .get(coinMarket)
            .then((resp) => {
              this.results = formatCoins(resp);
            });
    },

    getColor: (num) => {
        return num > 0 ? "color:green;" : "color:red;";
    },
  },
  created: function() {
      this.getCoins();
  }
})
setInterval(() => {
        newApp.getCoins();
    },
    updateInterval
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="coinApp">
    <div v-for="(record, index) in results" :key="index">
      {{index}} - {{record.name}}: {{record.rank}}
    </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多