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

Javascript Console.log将数组转换为逗号分隔的值,javascript,arrays,console,console.log,Javascript,Arrays,Console,Console.log,测试-1 let myArray = [1,2,3] function arrayCounter (array1) { console.log(`this is statement ${array1}`); } arrayCounter(myArray) O/p=>这是语句1,2,3 let myArray = [1,2,3] console.log(myArray) 测试-2 let myArray = [1,2,3] function arrayCounter2 (array1)

测试-1

let myArray = [1,2,3]
function arrayCounter (array1) {
    console.log(`this is statement ${array1}`);
}
arrayCounter(myArray)
O/p=>这是语句1,2,3

let myArray = [1,2,3]
console.log(myArray)
测试-2

let myArray = [1,2,3]
function arrayCounter2 (array1) {
    console.log("this is statement " + array1);
}
arrayCounter2(myArray)
O/p=>这是语句1,2,3

let myArray = [1,2,3]
console.log(myArray)
测试-3

let myArray = [1,2,3]
console.log(myArray)
O/p=>[1,2,3]

测试-1测试-2中,预期的O/p应为这是一种陈述[1,2,3]


那么,为什么会发生这种情况?我不理解一个场景。

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

让myArray=[1,2,3]

log(“”+myArray)
在测试1和2中,您的数组被转换为字符串:

让myArray=[1,2,3]

console.log(“”+myArray)
在测试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
ging一个字符串-您是在
console.log
ging一个数组,因此在控制台中,您将看到
[
]
指示正在记录的项是一个数组。

在测试1和测试2中,您将数组与一个字符串连接起来,这将导致调用
Array.prototype.valueOf
,返回用逗号连接的数组项,或
myArray.join(',')
So:

console.log(`this is statement ${array1}`);

console.log("this is statement " + array1);
这和

console.log("this is statement " + array1.join(','));

但是在测试3中,您不是在
console.log
ing一个字符串,而是在
console.log
ing一个数组,因此在控制台中,您将看到
[
]
指示要记录的项是一个数组。

在测试1中,数组被javascript转换成字符串。测试2也是如此。在测试3中,可以打印数组对象(不需要转换为字符串),并因此作为完整数组输出。在测试1中,数组通过javascript转换为字符串。测试2也是如此。在测试3中,可以打印数组对象(不需要转换为字符串),从而作为完整数组输出