簡體   English   中英

Javascript - 創建新數組而不是遞增

[英]Javascript - Creates new array instead of incrementing

我正在制作一個簡單的Twitter應用程序來處理我的JavaScript。 下面的代碼應該識別每個推文位置並計算每個位置的推文數量。

但是,它不會增加,只會創建一個新數組。 我的代碼出了什么問題? 我怎樣才能讓它變得更好?

謝謝

var Twitter = require('node-twitter'),
twit = {},
loc = [];

twit.count = 0;


var twitterStreamClient = new Twitter.StreamClient(
//credentials
);

twitterStreamClient.on('close', function () {
    console.log('Connection closed.');
});
twitterStreamClient.on('end', function () {
    console.log('End of Line.');
});
twitterStreamClient.on('error', function (error) {
    console.log('Error: ' + (error.code ? error.code + ' ' + error.message : error.message));
});
twitterStreamClient.on('tweet', function (tweet) {


    if (loc.indexOf(tweet.user.location) === -1) {
        loc.push({"location": tweet.user.location, "locCount": 1});
    } else {
        loc.loation.locCount = loc.loation.locCount + 1;
    }


    console.log(loc);

});

var search = twitterStreamClient.start(['snow']);

你需要重寫on tweet回調:

var index = loc.reduce(function(acc, current, curIndex) {
   return current.location == tweet.user.location ? curIndex : acc;
}, -1);

if (index === -1) {
    loc.push({"location": tweet.user.location, "locCount": 1});
} else {
    loc[index].locCount++;
}

Array.indexOf與您認為不匹配。 您正在創建一個新對象並將其推入數組,無論其屬性是否與其他對象完美匹配,它都不會===相等。 相反,你必須手動找到它:

var foundLoc;
for (var i = 0; i < loc.length; i++) {
  if (loc[i].location.x === location.x) 
     foundLoc = loc[i];
     break;
  }
}
if (!foundLoc) { 
  loc.push({location: location, count: 0});
} else {
  foundLoc.count++
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM