我在localstorage中保存了一组对象。
以下是对象数组的示例:
[{"mls":"1266159","addr":"13556 S TUSCALEE , Draper, UT 84020","price":"$1499000","description":"Bds: 7 | Ba: 7 | 10376 Sqft."},{"mls":"1279829","addr":"12927 S SALZ , Draper, UT 84020","price":"$779000","description":"Bds: 4 | Ba: 4 | 5857 Sqft."},{"mls":"1279960","addr":"14226 S CANYON VINE E, Draper, UT 84020","price":"$1899000","description":"Bds: 7 | Ba: 8 | 10015 Sqft."}]
我写了一个函数来获取数组,然后运行一个"每个"循环迭代对象并以指定的格式返回数组中的所有对象。
功能:
function getReportStore() {
var rs = localStorage.getItem("reportStore");
//console.log("Report Store: "+rs);
if((rs != null) && (rs != '')){
var r = JSON.parse(rs);
$.each(r, function (k, v) {
return "MLS: "+v.mls+" Address: "+v.addr+" Price: "+v.price+" Description: "+v.description;
});
}
}
尝试调用函数,并将数据返回到变量...
var p = getReportStore();
现在使用变量......
var report = "Properties Viewed: " + p;
console.log("The Report: "+report);
问题在于,当我尝试执行该函数以便将返回的对象用作变量时,它返回为" undefined"。
提前感谢您的建议/协助/指导/等等!
答案 0 :(得分:3)
看起来你没有从你的功能中返回任何东西。您从内部高阶$ .each函数返回,但这不会从getReportStore()返回。
试试这样:
function getReportStore() {
var rs = localStorage.getItem("reportStore");
//console.log("Report Store: "+rs);
if((rs != null) && (rs != '')){
var r = JSON.parse(rs);
return r.map(function (v) {
return "MLS: " +v.mls +
" Address: "+v.addr +
" Price: "+v.price +
" Description: " + v.description;
}).join('\n');
}
return "";
}
注意:我用标准数组映射
替换了jquery $ .each