为什么 Node.js 中的可选参数不需要 undefined 或 null?

问题描述 投票:0回答:2

请参阅 Node.js 文档中的 此示例

response.writeHead(statusCode[, statusMessage][, headers])
const body = 'hello world';
response
  .writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain',
  })
  .end(body);   

writeHead
函数的第二个参数应该是
statusMessage
。 为什么这第二个参数可以自动跳过,我们不需要参数为undefined或者null吗? Node.js 如何知道该对象是第三个参数?

为什么不:

const body = 'hello world';
response
  .writeHead(200, undefined, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain',
  })
  .end(body); 
javascript node.js
2个回答
0
投票

文档说:

最后一个参数 headers 是响应头。 (可选)可以提供人类可读的 statusMessage 作为第二个参数。

writeHead
函数的实现会检查第二个参数是
string
还是
object
,并做出相应的行为。您可以在源代码中看到它。

if (typeof reason === 'string') { // writeHead(statusCode, reasonPhrase[, headers]) // ... } else { // writeHead(statusCode[, headers]) // ... }
    

0
投票
在函数的代码中,它将查看参数的类型并确定要做什么

所以类似

const writeHead = (status, bodyOrHeaders, maybeHeaders) => { let body, headers; if (maybeHeaders) { // if we have a 3rd arg, we assume its the value for headers // and the body is the 2nd arg headers = maybeHeaders; body = bodyOrHeaders; } else { // otherwise we didnt get a 3rd arg so assume headers is 2nd body = null; headers = bodyOrHeaders; } // ... do something with status, body and headers }
    
© www.soinside.com 2019 - 2024. All rights reserved.