[英]Strange array behaviour in NodeJS
我为NodeJS编写了以下代码:
/* server.js */
'use strict';
const http = require('http'),
url = require('url');
METHODS = ['GET','POST','PUT','DELETE'],
_routePathIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),
_routeMethodIndex = _routePathIndex.slice(),
_server = http.createServer();
_server.on('request', (req, res) => {
let parsed = url.parse(req.url),
methodIndexVal = METHODS.indexOf(req.method),
PathIndexVal = _routePathIndex[methodIndexVal].indexOf(parsed.pathname);
_routeMethodIndex[methodIndexVal][PathIndexVal](req, res);
});
module.exports = _init();
function _init(){
let rs = { listen: _listen };
METHODS.forEach( (val,i) => {
rs[val.toLowerCase()] = function(route, handler){
_routePathIndex[i].push(route);
_routeMethodIndex[i].push(handler);
};
});
return rs;
};
function _listen(port, callback){
_server.listen(port, callback);
}
为了进行测试,我有一个非常简单的脚本:
/* server.test.js */
var app = require('./server.js');
app.get('/', (req,res) => { console.log(req, res); });
app.listen(3000, () => { console.log('listening at port', 3000) });
奇怪之处始于server.test.js的第2行,该代码在server.js中执行以下代码块,我添加了注释以显示_routePathIndex
和_routeMethodIndex
的值。
...
rs[val.toLowerCase()] = function(route, handler){
/* _routePathIndex: [ [], [], [], [], ]
_routeMethodIndex: [ [], [], [], [], ] */
_routePathIndex[i].push(route);
/* _routePathIndex: [ ['/'], [], [], [], ]
_routeMethodIndex: [ ['/'], [], [], [], ] */
_routeMethodIndex[i].push(handler);
/* _routePathIndex: [ ['/', [Function]], [], [], [], ]
_routeMethodIndex: [ ['/', [Function]], [], [], [], ] */
};
...
我的问题是,为什么作为数组的数组互相引用?
最初,我以为可能是.slice()
构成了引用,但我通过在同一环境中运行以下脚本来揭穿了这一点:
var a = [], b = a.slice();
a.push(1);
console.log(a,b); // [1] [0]
另一件事是当我不执行.slice()
技巧并将代码重构为这样的时候
...
_routePathIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),
_routeMethodIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),
奇怪的引用行为消失了,代码可以正常运行!
有关更多信息,我正在使用node -v
: v5.4.1
。
我也尝试使用[].concat(_routePathIndex)
克隆数组,但它仍然具有怪异的行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.