如何从stocks
broadcast
变量
var net = require('net');
var ReadWriteLock = require('rwlock');
var stocks = [
{symbol: "GM", open: 48.37},
{symbol: "GE", open: 29.50}
];
var server = net.createServer(function(socket) {
// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(data, socket);
});
function broadcast(message, sender) {
lock.readLock(function (release) {
....
maxChange = 100.0 * 0.005;
change = (maxChange - Math.random() * maxChange * 2);
stock = stocks[symbol],
maxChange = stock.open * 0.005,
....
//**How do I access stocks from here?**
});
release();
});
}
给出错误:
maxChange = stock.open * 0.005, ^
TypeError: Cannot read property 'open' of undefined
答案 0 :(得分:1)
您的代码暗示symbol
是数组的键,但事实并非如此。它是数组中某个对象的属性
使用此:
Array.prototype.myFind = function(obj) {
return this.filter(function(item) {
for (var prop in obj){
if (!(prop in item) || obj[prop] !== item[prop]){
return false;
}
}
return true;
});
};
// then use:
var arrayFound = stocks.myFind({'symbol':symbol});
这将找到对象的symbol
属性等于变量symbol
的数组元素
找到here