Мне нужен способ рекурсивной печати объекта, на который предоставлен ответ на страницу (спасибо!). Я немного обновил его, чтобы включить способ печати на определенный уровень, и добавить интервал так, чтобы он был правильно отступом на основе текущего уровня, в котором мы находимся, чтобы он был более читабельным.
// Recursive print of object
var print = function( o, maxLevel, level ) {
if ( typeof level == "undefined" ) {
level = 0;
}
if ( typeof level == "undefined" ) {
maxLevel = 0;
}
var str = '';
// Remove this if you don't want the pre tag, but make sure to remove
// the close pre tag on the bottom as well
if ( level == 0 ) {
str = '<pre>';
}
var levelStr = '';
for ( var x = 0; x < level; x++ ) {
levelStr += ' ';
}
if ( maxLevel != 0 && level >= maxLevel ) {
str += levelStr + '...</br>';
return str;
}
for ( var p in o ) {
if ( typeof o[p] == 'string' ) {
str += levelStr +
p + ': ' + o[p] + ' </br>';
} else {
str += levelStr +
p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
}
}
// Remove this if you don't want the pre tag, but make sure to remove
// the open pre tag on the top as well
if ( level == 0 ) {
str += '</pre>';
}
return str;
};
Использование:
var pagewilsObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
// Recursive of whole object
$('body').append( print(pagewilsObject) );
// Recursive of myObject up to 1 level, will only show name
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) );
Хотите что-то подобное? :
elementPos = {
row: 2,
column: 2
};
tableRows: number = 4;
tableColumns: number = 4;
ngOnInit() {
this.refreshTable();
}
refreshTable() {
tableHTML = '<table><tbody>';
for(let i=0;i<this.tableRows;i++) {
tableHTML += '<tr>';
for(let j=0;j<this.tableColumns;j++) {
if (this.elementPos.row === i && this.elementPos.column === j) {
tableHTML += '<td><div>My Element</div></td>';
} else {
tableHTML += '<td></td>';
}
}
tableHTML += '</tr>';
}
document.querySelector('#myTableDiv').innerHTML = tableHTML;
}
updateElePosOnInput(val) {
switch(val) {
case 1:
this.elementPos.row -= 1;
break;
case 2:
this.elementPos.row += 1;
break;
default:
this.elementPos.row = 2;
this.elementPos.column = 2;
};
this.refreshTable();
}