localStorage按值排序 [英] localStorage sort order by value

查看:585
本文介绍了localStorage按值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将一些数据放在localStorage中,并且我想检索数组中的键名,并按值排序:

I've put some data in localStorage, and I want to retrieve to key names in an array, ordered by the value:

法国:0
意大利:1
英格兰:2
德国:3
..等

France : 0
Italy: 1
England: 2
Germany: 3
.. etc.

function getCountries() {
    "use strict";
    var returnArray = [];
    for (var i = 0; i < localStorage.length; i++) {
        returnArray.push(localStorage.key(i));
    }

    return returnArray;
}

现在,数组中键名的顺序似乎是非常随机的-如何通过值对数组进行排序?

Right now the order of the key-names in the array seems to be quite random - how to order the array by the values?

推荐答案

如果要在多个位置进行排序,则可以创建原型.

If you want to sort in multiple places you can create a prototype.

Array.prototype.sortOnValue = function(key){
    this.sort(function(a, b){
        if(a[key] < b[key]){
            return -1;
        }else if(a[key] > b[key]){
            return 1;
        }
        return 0;
    });
}

创建了小提琴,介绍了如何使用它.

Created a fiddle of how to use it.

这篇关于localStorage按值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆