7

JavaScript array value of the method

 3 years ago
source link: https://www.codesd.com/item/javascript-array-value-of-the-method.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript array value of the method

advertisements

[].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"

Tags javascript

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK