我有这个功能:
function addToArray() {
var thesesArrays = []; // an empty array
var sometheses = ["With I/O Speech, Larry Page Reminds Us Why Google Rules Tech", "Tech", "myID_xGr52srsiwi"];
thesesArrays.push(sometheses); // the empty array gains one array
Logger.log("thesesArrays[0][1] = " + thesesArrays[0]);
Logger.log("thesesArrays = " + thesesArrays);
}
我是 JS 编程(和一般编程)的新手,所以这似乎是一个非常新手的问题。为什么 thesesArrays[0][1]
和 thesesArrays
的日志相同?
thesesArrays
日志不应该是这样的:[["With I/O Speech, Larry Page Reminds Us Why Google Rules Tech", "Tech", "myID_xGr52srsiwi"] ]
?
最佳答案
您对它们的理解是正确的。
在 JavaScript 中,扩展 native 对象类型的对象有一个 toString()
方法,该方法旨在将该实例表示为 String
。碰巧的是,当您在数组上调用 toString()
时,您会得到数组元素的所有 toString()
值,它们之间有一个逗号。
在您第一次调用 Logger.log()
时,您将内存中表示的内容传递给它:
["With I/O Speech, Larry Page Reminds Us Why Google Rules Tech", "Tech", "myID_xGr52srsiwi"]
如果你在这个数组上调用 toString()
,你会得到字符串:
"With I/O Speech, Larry Page Reminds Us Why Google Rules Tech,Tech,myID_xGr52srsiwi"
这是对所有元素调用 toString()
的结果(因为它们是 字符串而返回自己),然后添加 ,
介于两者之间。
在您的第二次调用中,您提供包含数组 thesesArrays
。同样的逻辑在这里适用,因为它递归地遵循与上述相同的逻辑,但是因为 Array
只有一个元素(它本身是一个 Array
),所以没有需要用逗号分隔。
为了证明这一点,让我们在父数组 thesesArrays
中添加另一个数组:
thesesArrays.push('my second array'.split(' '))
现在,如果您在 thesesArrays
上调用 toString()
,您会看到我们的新数组已添加到末尾,并以逗号分隔:
"With I/O Speech, Larry Page Reminds Us Why Google Rules Tech,Tech,myID_xGr52srsiwi,my,second,array"
供引用:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
关于javascript - 在javascript中,array = []是否等于array = [[]]?如果不是,为什么会有这种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124100/