При передаче объекта document.write, JavaScript преобразует объект в строку с .ToString(). В этом случае Array.toString() будет сглаживаться и присоединяться к массиву с запятыми и возвращать его как строку.
["this", "is", "an", "array!"].toString(); // "this,is,an,array!"
[["a",["b"]], ["c"]].toString() // "a,b,c"
Мы можем расширить document.write([["a",["b"]], ["c"]])
в следующее:
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"
Я думаю, что он использует 'toString()' not 'valueOf()' –
, ваш образец edit возвращает 'a, b' и no, последний возвращает' a, b', потому что '[] .toString()' переводит все его элементы в строку перед конкатенацией - вложенные массивы будут рекристаллизованы. –