简单的web服务器示例-为什么我必须将属性名称加引号

Simple web server example - why do I have to put the property name in quotes?

本文关键字:属性 加引号 为什么 web 服务器 简单      更新时间:2023-09-26

考虑以下示例:

var http = require('http');
var server = http.createServer(function(request, response) {
  response.writeHead({
    'content-type': 'text/plain'
  });
  response.end('Hello world!');
});
server.listen(8000);

为什么必须将content-type属性名称加引号?writeHead不需要一个普通的JS对象吗?为什么我不能写这样的东西:

{
  content-type: 'text/plain'
}

如果JavaScript对象文字的属性名称不是有效的标识符(即可以用作变量名的名称),则必须引用该名称;整数显然也可以。由于短划线字符(-)不是标识符的有效部分,因此必须在字符串中加引号。

var o;
o = {content-type: 'text/plain'}; // => SyntaxError: Unexpected token "-"
o = {'content-type': 'text/plain'}; // => OK
o = {contentType: 'text/plain'}; // => OK
o = {123: 456}; // => OK
o = {$x: 123}; // => OK
o = {π: 234}; // => OK