Last active
March 6, 2017 06:10
-
-
Save ecmadao/09acaac7190ffca398aa76fedd0ccb4e to your computer and use it in GitHub Desktop.
Arguments in javascript functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ========================= ES5 中的 arguments ====================== */ | |
// 在 ES5 中,一个函数内的 arguments 关键字可以获取该函数在调用时受到的所有参数 | |
function foo() { | |
// get arguments of a function | |
for (var i = 0; i < arguments.length; i++) { | |
console.log(arguments[i]); | |
} | |
} | |
function boo() { | |
// get arguments of a function | |
console.log(arguments); | |
} | |
boo(1, 2, 3, 4); // [1, 2, 3, 4] | |
// 但要注意的是,arguments 很像 Array,也拥有 length 属性,但实际上只是一个类 Array 对象,并不具有 Array 的其他方法。 | |
// 如果想要使用 Array 的操作,则需要做相关处理 | |
// convert arguments to real Array | |
function sortArgs() { | |
var args = Array.prototype.slice.call(arguments); | |
return args.sort(); | |
} | |
/* ========================= ES6 中的 arguments ====================== */ | |
// ES6 没有 arguments 属性,但是鉴于 ES6 的箭头函数和不定参数,我们可以直接拿到一个函数的所有参数 | |
const func = (...args) => { | |
console.log(args); | |
const max = Math.max(...args); | |
console.log(max); | |
}; | |
func(1, 2, 3, 4, 5); | |
// [1, 2, 3, 4, 5] | |
// 5 |
Author
ecmadao
commented
Feb 2, 2017
- JavaScript variable number of arguments to function
- How can I convert the “arguments” object to an array in JavaScript?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment