Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array valueOf method

Tags:

javascript

[].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
like image 288
Maizere Pathak.Nepal Avatar asked Jun 22 '13 03:06

Maizere Pathak.Nepal


3 Answers

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"
like image 78
SpenserJ Avatar answered Oct 09 '22 18:10

SpenserJ


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

like image 20
raam86 Avatar answered Oct 09 '22 16:10

raam86


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.

like image 29
PSL Avatar answered Oct 09 '22 17:10

PSL