-
函数参数如果是基本类型(string\number\boolean),传递方式为传值传递。在函数内部改变参数,不会影响到外部
const p = 2 function test (p) { p = 3 } test(p) console.log(p) // p = 2
如果参数是符合类型的值(object\array\function),传递方式为地址传递,在函数内部改变函数值,会影响原始值。如果是整个替换了参数,原始值不变(传入的实际上是o的地址,重新赋值导致o指向新的地址,原地址的值不受影响)
const obj = [1, 2, 3] function f (o) { o = [3, 4, 5] } f(obj) console.log(obj) // obj = [3, 4, 5]
-
arguments 是一个对象,数组专有的方法(比如slice和forEach),不能在arguments对象上直接使用。
如果要让arguments对象使用数组方法,真正的解决方法是将arguments转为真正的数组。下面是两种常用的转换方法:slice方法和逐一填入新数组const args = Array.prototype.slice.call(arguments); // 或者 let args = []; for (const i = 0; i < arguments.length; i++) { args.push(arguments[i]); }
JavaScript基础回顾
最新推荐文章于 2023-05-09 19:08:55 发布