gpt4 book ai didi

javascript - NodeJS 中奇怪的数组行为

转载 作者:搜寻专家 更新时间:2023-11-01 00:23:07 26 4
gpt4 key购买 nike

我为 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) 克隆数组,但它仍然有奇怪的行为

最佳答案

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

a = [[],[]];
b = a.slice();

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

获取图片:

enter image description here

关于javascript - NodeJS 中奇怪的数组行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35526704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com