参数 arguments

未匹配的标注

函数体内可通过 arguments 对象访问参数数组。

arguments 对象与数组类似 (它并不是 Array 的实例)

function eat() {
    console.log(arguments);
    console.log(arguments[0]);
}
eat('鸡蛋','花生米');

参数 argument

命名的参数只提供便利,但不是必需的。

function response(status, body) {
  console.log(arguments);
}
response(200);

参数 argument

访问 argumentslength 属性可以获知有多少个参数传递给了函数。我们可以利用该属性模仿 Java 中的 ⌈重载⌋。

function response() {
  let resp = {
    status: 200,
    msg: 'success',
    body: null
  }
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      if (Object.prototype.toString.call(arguments[0]) === '[object Object]') {
        resp.body = arguments[0];
      } else {
        resp.msg = arguments[0];
      }
      break;
    case 2:
      resp.status= arguments[0];
      resp.msg = arguments[1];
      break;
    case 3:
      resp.status = arguments[0];
      resp.msg = arguments[1];
      resp.body = arguments[2];
      break;
    default:
      resp.code=500;
      resp.msg='fail';
  }
  return resp;
}
console.log(response()); 
//{status: 200, msg: 'success', body: null}

console.log(response('opration success')); 
//{status: 200, msg: 'opration success', body: null}

console.log(response({name:'bruce'})); 
//{status: 200, msg: 'success', body: {name: 'bruce'}}

console.log(response(1001, 'opration error')); 
//{status: 1001, msg: 'opration error', body: null}

console.log(response(1002, 'opration error', {url: 'http://redirect'})); 
//{status: 1002, msg: 'opration error', body: {url: 'http://redirect'}}

扩展 php

function arg() {
  print_r(func_get_args());
}
arg(['status' => 'ok'], 200);

Array
(
    [0] => Array
        (
            [status] => ok
        )

    [1] => 200
)

亦可参照 ⌈重载⌋ 的示例封装方便的响应函数。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~