javascript - 在javascript中,array = []是否等于array = [[]]?如果不是,为什么会有这种行为?

标签 javascript arrays google-apps-script

我有这个功能:

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 的日志相同?

enter image description here

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/

相关文章:

javascript - 以 JSON 格式创建 res.cookie,并将值作为对象

javascript - DIV 类错误

c - 如何用前导零填充整数打印?

javascript - 谷歌应用程序脚本sendEmail发送多封电子邮件

javascript - JS自定义缓存功能?

JavaScript 鼠标悬停事件与单击事件

arrays - 将数据库中现有的字符串字段类型转换为数组字段类型 | Rails + PostgreSQL

javascript - 按人工顺序对 JavaScript 数组进行排序

google-apps-script - 在 Google Sheets 中使用范围参数智能填写自定义函数

google-apps-script - 如何从 GAS 的文本框中获取文本?