我正在尝试用html打印数组,但是我的for循环无法正常工作。我正在尝试获取dataArrayNew
的长度,但是它没有返回添加我的for循环的位置。如果我console.log(dataArrayNew.title);
,我可以看到正确的结果。我还要附加浏览器控制台的打印屏幕。
var dataArrayNew = [];
function fetch_section_data_1(){
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
dataArrayNew = JSON.parse(localStorage.getItem(key));
console.log(dataArrayNew.title);
//lengtharray = dataArrayNew.length;
//console.log(lengtharray);
//return JSON.parse(localStorage.getItem(key));
});
var $table = $( "<table></table>" );
for(i=0;i<dataArrayNew.length;i++){
var array_no = dataArrayNew[i];
var $line = $( "<tr></tr>" );
$line.append( $( "<td></td>" ).html( array_no.title ) );
$table.append( $line );
console.log(dataArrayNew.title);
}
$table.appendTo(document.body);
}
最佳答案
之所以看不到length
属性,是因为您正在将dataArrayNew
从数组重新分配给作为对象的结果JSON.parse
,并且对象没有属性length
。与其重新分配dataArrayNew
的值,不如为什么将JSON.parse(localStorage.getItem(key))
的值推给它,就像这样:
dataArrayNew.push(JSON.parse(localStorage.getItem(key)));
因此,您的代码应如下所示:
var dataArrayNew = [];
function fetch_section_data_1(){
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
var currIn = JSON.parse(localStorage.getItem(key));
console.log(currIn);
// push data to dataArrayNew
dataArrayNew.push(currIn);
//lengtharray = dataArrayNew.length;
//console.log(lengtharray);
//return JSON.parse(localStorage.getItem(key));
});
var $table = $( "<table></table>" );
// You should be able to get the length here now
for(var i = 0; i < dataArrayNew.length; i++){
var array_no = dataArrayNew[i];
var $line = $( "<tr></tr>" );
$line.append( $( "<td></td>" ).html( array_no.title ) );
$table.append( $line );
console.log(dataArrayNew.title);
}
$table.appendTo(document.body);
}