简体   繁体   English

NodeJS中的奇怪数组行为

[英]Strange array behaviour in NodeJS

I have the following code written for 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);
}

To test this out I have the I have a very simple script: 为了进行测试,我有一个非常简单的脚本:

/* 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) });

The strangeness begins on line 2 of server.test.js which executes the following code block in server.js, I added the comments to display the values of both _routePathIndex and _routeMethodIndex . 奇怪之处始于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]], [], [], [], ] */
        }; 
...

My question is, why is the array acting as tho there are referenced to each other? 我的问题是,为什么作为数组的数组互相引用?

At first, I thought maybe it was the .slice() that was making the reference but I debunked that by running the following script in the same environment: 最初,我以为可能是.slice()构成了引用,但我通过在同一环境中运行以下脚本来揭穿了这一点:

var a = [], b = a.slice();
a.push(1);
console.log(a,b); // [1] [0]

Another thing is when I don't do the .slice() trick and refactored the code to as such 另一件事是当我不执行.slice()技巧并将代码重构为这样的时候

...
    _routePathIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),
    _routeMethodIndex = Array.apply(null, Array(METHODS.length)).map(() => {return []}),

the strange referencing behaviour is gone and the code works Perfect! 奇怪的引用行为消失了,代码可以正常运行!

For added info I'm working with node -v : v5.4.1 . 有关更多信息,我正在使用node -vv5.4.1

Also I tried to clone the array using [].concat(_routePathIndex) but it still had that weird behaviour 我也尝试使用[].concat(_routePathIndex)克隆数组,但它仍然具有怪异的行为

slice only does a shallow copy, that is _routePathIndex and _routeMethodIndex are different, but their elements are the same. slice仅做一个浅表副本,即_routePathIndex_routeMethodIndex不同,但是它们的元素相同。 Consider this simplified example: 考虑以下简化示例:

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

Get a picture: 获取图片:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM