0
点赞
收藏
分享

微信扫一扫

JavaScript-函数 arguments

因为 ​​console.log();​​​ 也是通过 ​​()​​​ 来调用的, 所以 ​​log​​ 也是一个函数。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
console.log();

function say() {
console.log("hello world");
}

window.say();
</script>
</head>
<body>
</body>
</html>

​log​​​ 函数的特点,可以接收 ​​1​​​ 个或 ​​多个​​ 参数。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
console.log(1);
console.log(1, 2);
console.log(1, 2, 3);
</script>
</head>
<body>
</body>
</html>

为什么 log 函数可以接收 1 个或多个参数呢?内部的实现原理就用到了 ​​arguments​​。

arguments 的作用

保存所有传递给函数的实参。????注意点:每个函数中都有一个叫做 ​​arguments​​ 的东东,arguments 其实是一个伪数组。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
function getSum() {
console.log(arguments);
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);

let sum = 0;
for (let i = 0; i < arguments.length; i++) {
let num = arguments[i];
sum += num;
}
return sum;
}

let res = getSum(10, 20, 30, 40);
console.log(res);
</script>
</head>
<body>
</body>
</html>

JavaScript-函数 arguments_数组




举报

相关推荐

0 条评论