[].valueOf()
method retuns array itself.According to this
document.write([["a"]],["b"])
should return ['a']b isn't it?But this is not happening ,it just writes ab
.I just wanted to know the reason behind this.
For string elements .toString() method returns this,
["a","b"].toString()//a,b
But for elements with array it should return
[["a"],"b"].toString()//[a],b
When you pass an object to document.write, Javascript converts the object to a string with .toString(). In this case, Array.toString() will flatten and join the array with commas, and return it as a string.
["this", "is", "an", "array!"].toString(); // "this,is,an,array!"
[["a",["b"]], ["c"]].toString() // "a,b,c"
We can expand document.write([["a",["b"]], ["c"]])
into the following:
var input = [["a",["b"]], ["c"], "d"];
Array.prototype.verboseToString = function verboseToString() {
// Make a copy of the array, so we don't destroy the original
var copy = this.slice(), i;
for (i = 0; i < copy.length; i++) {
// If this is an Array, call verboseToString() on it, and go deeper
if (copy[i] instanceof Array === true) {
copy[i] = copy[i].verboseToString();
}
}
// copy contains non-arrays and we're ignoring other types' toString() output
return copy.join(',');
}
document.write(input.verboseToString()); // "a,b,c,d"
document.write([["a"]]",",["b"])
write get unlimited arguments separated by commas so it is actually expected behavior
In order to print what you want use:
document.write(["a","b"])
This way you will print an array and not a list of arrays
From docs
The text you write is parsed into the document's structure model.
So you send out an array it will just evaluate the array values to string to create a document structure which [["a"]],["b"]
has none but just the text values.
If you do this:
document.write(["<a>a</a>", "<a>b</a>"])
You can see it creates 2 anchor elements separated by ,
so its just array.join(',')
or just provide this:
document.write(["<a>a</a>"], ["<a>b</a>"])
This time it will create 2 anchors you don't see a comma anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With