全球范围&命名空间

时间:2017-02-08 00:31:50

标签: node.js

如何从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

1 个答案:

答案 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