Fabian said:
I have a three tier nested array, ...
a) create the string in a form that a html parser can
display as ready-formatted javascript code
Wrapping the JavaScript source code in <PRE> tags is one obvious way of
presenting pre formatted source code text in HTML.
One way of simply getting nested arrays back to source code form might
be to provide the Array objects with custom toString methods that
overload Array.prototype.toString and return a source code string
representation of the array. That is not without its problems as there
are limitations on the degree to which you can mix the types of contents
in the array, especially mixing strings with other types. This example
demonstrates:-
<html>
<head>
<title></title>
<script type="text/javascript">
function getToStringForStringArray(tabDepth){
var st = ''
for(var c = tabDepth;c--
{
st += '\t';
}
return (function(){
return '[\n'+st+'\t\''+this.join(('\',\n'+st+'\t\''))+
'\'\n'+st+']';
});
}
function getToStringForNonStringArray(tabDepth){
var st = ''
for(var c = tabDepth;c--
{
st += '\t';
}
return (function(){
return '[\n\t'+st+this.join((',\n'+st+'\t'))+'\n'+st+']';
});
}
var a = [
[
[
1,
2,
3,
4,
5,
6
],
[
'a',
'b',
'c',
'd',
'e',
'f',
'g'
]
],
[
12,
13,
14,
15
],
[
'a',
'b',
'c',
'd',
'e',
'f',
'g'
],
[
true,
false,
true,
true
]
];
a.toString = getToStringForNonStringArray(1);
a[0].toString = getToStringForNonStringArray(2);
a[1].toString = getToStringForNonStringArray(2);
a[2].toString = getToStringForStringArray(2);
a[3].toString = getToStringForNonStringArray(2);
a[0][0].toString = getToStringForNonStringArray(3);
a[0][1].toString = getToStringForStringArray(3);
</script>
</head>
<body>
<pre>
<script type="text/javascript">
document.write('var a = '+a+';\n')
</script>
</pre>
</body>
</html>
If you don't need the tabulation the process becomes considerably
simpler.
Lee's method for getting the string into a new window is a good as any
(and better than most, though it does still fail on IceBrowser 5 [1], as
do all other methods of writing HTML strings into pop-ups on that
browsers).
Richard.
[1] IceBrowser's javascript: pseudo-protocol implementation is very odd
as, while it will execute side-effect function calls, it does not use
the return value of the expression used (if present) as replacement HTML
source for targeted window/frame. It looks like they designed the
behaviour around the (generally considered incorrect) common use of
javascript: URLs instead of the behaviour of existing implementations.
Still, I have never been able to find a specification of how javascript
URLs should be handled so it is difficult to say that any particular
implementation is wrong.