测试 1
let myArray = [1,2,3]
function arrayCounter (array1) {
console.log(`this is statement ${array1}`);
}
arrayCounter(myArray)
O/P => this is statement 1,2,3
测试 2
let myArray = [1,2,3]
function arrayCounter2 (array1) {
console.log("this is statement " + array1);
}
arrayCounter2(myArray)
O/P => this is statement 1,2,3
测试 3
let myArray = [1,2,3]
console.log(myArray)
O/P => [1,2,3]
在 test-1 和 test-2 中,预期的 O/P 应该是这样的语句 [1,2,3]
那么,为什么会发生这种情况?我不明白场景。
最佳答案
在测试 1 和测试 2 中,您将数组与字符串连接起来,这会导致调用 Array.prototype.valueOf
,它返回由逗号连接的数组项,或 myArray.join(',')
所以:
console.log(`this is statement ${array1}`);
与
相同console.log("this is statement " + array1);
与
相同console.log("this is statement " + array1.join(','));
但在测试 3 中,您不是在 console.log
中处理字符串,而是在 console.log
中处理数组,因此在控制台中,您将看到 [
和 ]
指示正在记录的项目是一个数组。
关于javascript - Console.log 将数组转换为逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53667388/