NodeJS中奇怪的数组行为

时间:2016-02-20 17:37:49

标签: 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);
}

为了测试这个,我有一个非常简单的脚本:

/* 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 -vv5.4.1

我还尝试使用[].concat(_routePathIndex)克隆数组,但它仍然有那种奇怪的行为

1 个答案:

答案 0 :(得分:5)

slice只有浅版本,即_routePathIndex_routeMethodIndex不同,但它们的元素是相同的。考虑这个简化的例子:

a = [[],[]];
b = a.slice();
    
b[0].push(1);
document.write(a)

获取图片:

enter image description here