[英]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.