1

我有一个功能可以获取本地存储的所有密钥并通过电子邮件将其发送给您:

function sendLocalStorageByEmail(recipient) {
// create localstorage string
var output = "";


for (var key in localStorage) {
    output += key + "\n";
    output += localStorage[key] + "\n";
    output += "\n";
}

// create temporary anchor to emulate mailto click in new tab
var anchor = document.createElement("a");
anchor.href = "mailto:" + recipient + "?subject=Names for tonight&body=" + encodeURIComponent(output);
anchor.style.display = "none";
anchor.setAttribute("target", "_blank");
anchor.appendChild(document.createTextNode(""));
document.body.appendChild(anchor);

if (anchor.click) {
    return anchor.click();
}

由于键是一个四位数字,我想先按数字顺序对它们进行排序。我的问题是,由于本地存储数据存储为字符串,并且大多数排序都是通过数组完成的。我是否必须将其转换为数组,然后再返回?

如果有人可以帮助我,将不胜感激。

4

2 回答 2

2
function sendLocalStorageByEmail(recipient) {
    var output = '',
        arr = [],
        anchor = document.createElement("a");

    for (key in localStorage) {
        if (localStorage.hasOwnProperty(key) && !isNaN(key)) {
            arr.push(key);
        }
    }

    arr.sort(function(a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });

    for (var i=0; i<arr.length; i++) {
        output += arr[i] + "\n" + localStorage[arr[i]] + "\n\n";
    }

    anchor.href = "mailto:" + recipient + "?subject=Names for tonight&body=" + encodeURIComponent(output);
    anchor.style.display = "none";
    anchor.setAttribute("target", "_blank");
    anchor.appendChild(document.createTextNode(""));
    document.body.appendChild(anchor);

    if (anchor.click) {
        return anchor.click();
    }
}​
于 2012-12-07T04:32:15.400 回答
1

也许你可以这样尝试:-

var output = [];

for (var key in localStorage) {
    output.push(localStorage[key]);
}
output.sort();
var result=output.join();
var len = result.length;
var formatresult;
for (var i=0; i<len; i++) {
formatresult+= result[i]+ "\n";
}
于 2012-12-07T04:08:10.480 回答