Array.prototype.slice.call(arguments)

本文介绍了JavaScript中如何使用Array.prototype.slice.call()方法将类数组对象,如arguments或DOM元素集合,转换为真正的数组。通过示例展示了在处理getElementsByClassName返回的HTMLDOM集合时,如何利用该技巧进行数组操作,如forEach循环,以进行元素的尺寸计算和存储。

Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)

  • 例如: auguments是类数组,不是数组

HTML DOM集合转化成数组对象

const lis = this.$refs.foodsWarpperUl.getElementsByClassName('food-list')
      // Array.prototype.slice.call(arguments)将传入的arguments转化为数组
Array.prototype.slice.call(lis).forEach((el)=>{
    top += el.clientHeight
    tops.push(top)
})
### 使用 Array.prototype.slice.callarguments 转换为数组的方法和场景 在 JavaScript 中,`arguments` 是一个类数组对象,它包含了函数调用时传递的所有参数。由于 `arguments` 不是真正的数组,因此无法直接使用数组方法(如 `forEach`、`map` 等)。为了将 `arguments` 转换为真正的数组,可以使用 `Array.prototype.slice.call(arguments)` 方法[^1]。 #### 方法解析 `Array.prototype.slice.call(arguments)` 的作用是借用数组的 `slice` 方法来操作 `arguments` 对象,并将其转换为真正的数组。具体来说: - `Array.prototype.slice` 是数组原型上的方法,用于从已有的数组中返回选定的元素。 - `call` 是函数的一个方法,用于改变函数内部的 `this` 指向。在这里,`call` 将 `Array.prototype.slice` 的 `this` 指向了 `arguments` 对象。 - 通过这种方式,`arguments` 可以被当作数组来处理,从而实现类数组到真数组的转换[^4]。 #### 示例代码 以下是一个简单的示例,展示如何使用 `Array.prototype.slice.call` 将 `arguments` 转换为数组: ```javascript function convertArgumentsToArray() { // 使用 Array.prototype.slice.callarguments 转换为数组 const args = Array.prototype.slice.call(arguments); return args; } console.log(convertArgumentsToArray(1, 2, 3, 4)); // 输出: [1, 2, 3, 4] ``` #### 场景应用 1. **遍历所有参数**:当需要对函数的所有参数进行统一处理时,可以先将 `arguments` 转换为数组,然后使用数组方法(如 `forEach` 或 `map`)进行操作[^2]。 ```javascript function sumAll() { const args = Array.prototype.slice.call(arguments); return args.reduce((acc, num) => acc + num, 0); } console.log(sumAll(1, 2, 3, 4)); // 输出: 10 ``` 2. **实现 rest 参数的功能(兼容旧版本浏览器)**:在 ES6 引入 rest 参数之前,可以通过 `Array.prototype.slice.call(arguments)` 实现类似功能[^3]。 ```javascript function concatStrings() { const args = Array.prototype.slice.call(arguments); return args.join(' '); } console.log(concatStrings('Hello', 'world', '!')); // 输出: "Hello world !" ``` 3. **结合高阶函数**:在需要对 `arguments` 进行复杂处理时,可以将其转换为数组后与高阶函数配合使用。 ```javascript function filterEvenNumbers() { const args = Array.prototype.slice.call(arguments); return args.filter(num => num % 2 === 0); } console.log(filterEvenNumbers(1, 2, 3, 4, 5)); // 输出: [2, 4] ``` #### 注意事项 - 如果只需要部分参数,可以在 `slice` 方法中传入起始索引。例如,`Array.prototype.slice.call(arguments, 1)` 表示从第二个参数开始转换为数组[^4]。 - 在现代 JavaScript 中,推荐使用 rest 参数(`...args`),因为它语法更简洁且性能更好。但当需要兼容旧版本浏览器时,仍可使用 `Array.prototype.slice.call(arguments)`[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值