简介
(array-lick) 类数组对象中(长的像是一个数组, 本质上是一个对象): arguments 拥有数组的一些特性, 比如说length, 比如可以通过index索引来访问; // 但是它却没有数组的一些方法, 比如forEach、 map等;
基础用法
function foo(num1, num2, num3) {
//(array-lick) 类数组对象中(长的像是一个数组, 本质上是一个对象): arguments
// console.log(arguments)
// 拥有数组的一些特性, 比如说length, 比如可以通过index索引来访问;
// 但是它却没有数组的一些方法, 比如forEach、 map等;
// 常见的对arguments的操作是三个
// 1.获取参数的长度
console.log(arguments.length)
// 2.根据索引值获取某一个参数
console.log(arguments[2])
console.log(arguments[3])
console.log(arguments[4])
// 3.callee获取当前arguments所在的函数
console.log(arguments.callee)
// arguments.callee()
}
foo(10, 20, 30, 40, 50)
arguments转成数组
function foo(num1, num2) {
// 1.自己遍历
// var newArr = []
// for (var i = 0; i < arguments.length; i++) {
// newArr.push(arguments[i] * 10)
// }
// console.log(newArr)
// 2.arguments转成array类型
// 2.1.自己遍历arguments中所有的元素
// 2.2.Array.prototype.slice将arguments转成array
var newArr2 = Array.prototype.slice.call(arguments)
console.log(newArr2)
var newArr3 = [].slice.call(arguments)
console.log(newArr3)
// 2.3.ES6的语法
var newArr4 = Array.from(arguments)
console.log(newArr4)
var newArr5 = [...arguments]
console.log(newArr5)
}
foo(10, 20, 30, 40, 50)
// 额外补充的知识点: Array中的slice实现
// Array.prototype.myslice = function(start, end) {
// var arr = this
// start = start || 0
// end = end || arr.length
// var newArray = []
// for (var i = start; i < end; i++) {
// newArray.push(arr[i])
// }
// return newArray
// }
// var newArray = Array.prototype.myslice.call(["aaaa", "bbb", "cccc"], 1, 3)
// console.log(newArray)
// var names = ["aaa", "bbb", "ccc", "ddd"]
// names.slice(1, 3)
箭头函数不绑定arguments
// 1.案例一:
// var foo = () => {
// console.log(arguments)
// }
// foo()
// 2.案例二:
// function foo() {
// var bar = () => {
// console.log(arguments)
// }
// return bar
// }
// var fn = foo(123)
// fn()
// 3.案例三:
var foo = (num1, num2, ...args) => {
console.log(args)
}
foo(10, 20, 30, 40, 50)
剩余参数
// rest parameters
function sum(...nums) {
console.log(nums)
}
sum(10)//[10]
sum(10, 20) //[10, 20]
sum(10, 20, 30)//[10, 20, 30]
sum(10, 20, 30, 40, 50)//[10, 20, 30, 40, 50]
// 展开运算符 spread
var names = ["abc", "cba", "nba"]
// var newNames = [...names]//展开运算符spread
function foo(name1, name2, name3) {}
foo(...names)