JavaScript基础:函数、数组与对象的使用
1. 函数的使用
在JavaScript中,函数的参数类型由调用函数时使用的值决定。例如,下面的代码定义了一个 sumPrices 函数:
let hatPrice = 100;
console.log(`Hat price: ${hatPrice}`);
let bootsPrice = "100";
console.log(`Boots price: ${bootsPrice}`);
function sumPrices(first, second, third) {
return first + second + third;
}
let totalPrice = sumPrices(hatPrice, bootsPrice);
console.log(`Total Price: ${totalPrice}`);
上述代码的输出结果为:
Hat price: 100
Boots price: 100
Total Price: 100100undefined
这是因为JavaScript不会强制函数定义的参数数量与调用时使用的参数数量匹配。如果没有为某个参数提供值,该参数将为 undefined 。而且,当 + 运算符应用于字符串值时,会执行字符串拼接操作。
2. 函数结果的类型
函数调用时使用的参数可以决定函数结果的类型,如下所
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



