jkr*_*ris 2 javascript arrays node.js
我为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);
}
Run Code Online (Sandbox Code Playgroud)
为了测试这个,我有一个非常简单的脚本:
/* 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) });
Run Code Online (Sandbox Code Playgroud)
陌生开始在其上server.js执行下面的代码块server.test.js的第2行,我增加了要显示的评论两者的值_routePathIndex
和_routeMethodIndex
.
...
rs[val.toLowerCase()] = function(route, handler){
/* _routePathIndex: [ [], [], [], [], ]
_routeMethodIndex: [ [], [], [], [], ] */
_routePathIndex[i].push(route);
/* _routePathIndex: [ ['/'], [], [], [], ]
_routeMethodIndex: [ ['/'], [], [], [], ] */
_routeMethodIndex[i].push(handler);
/* _routePathIndex: [ ['/', [Function]], [], [], [], ]
_routeMethodIndex: [ ['/', [Function]], [], [], [], ] */
};
...
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么作为tho的数组彼此引用?
起初,我想也许.slice()
正在制作引用但我通过在相同的环境中运行以下脚本来揭穿它:
var a = [], b = a.slice();
a.push(1);
console.log(a,b); // [1] [0]
Run Code Online (Sandbox Code Playgroud)
另一件事是当我不做.slice()
技巧并重构代码时
...
_routePathIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),
_routeMethodIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),
Run Code Online (Sandbox Code Playgroud)
奇怪的引用行为消失了,代码完美无缺!
有关我正在使用的附加信息node -v
:v5.4.1
.
此外,我尝试使用克隆数组,[].concat(_routePathIndex)
但它仍然有这种奇怪的行为
slice
只做一个浅拷贝,也就是_routePathIndex
和_routeMethodIndex
不同,但它们的元素是相同的.考虑这个简化的例子:
a = [[],[]];
b = a.slice();
b[0].push(1);
document.write(a)
Run Code Online (Sandbox Code Playgroud)
得到一张图片: