Console.log 将数组转换为逗号分隔值

Console.log convert array to comma separated value

测试-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-1test-2中预期O/P应该是这样的语句[1,2,3 ]

那么,为什么会这样?我不明白一个场景。

在测试 1 和 2 中,您的数组被转换为字符串:

let myArray = [1,2,3]
console.log('' + myArray)

在测试 1 和测试 2 中,您将数组与字符串连接,这导致 Array.prototype.valueOf 被调用,returns 数组项由逗号连接,或 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 生成一个 数组 ,所以在控制台中,您会看到 [] 表示正在记录的项目是一个数组。