为什么具有内容的数组的数组长度为零?

时间:2018-06-04 10:19:36

标签: javascript arrays node.js electron

这是我的代码:

<script type="text/javascript" src="read.js"></script>
<script>
  var beats=[]
  beats=read('heartRate.txt')
  console.log(beats)           //label 1
  console.log(beats.length)    //label 2
  for (i = 0; i < beats.length; i++) { 
    console.log(beats[i])
    if(parseInt(beats[i])>80 || parseInt(beats[i])<50){
      document.getElementById('Alert').innerHTML('Abnormal heartrate of '+parseInt(beats[i]))
    }
  }
  console.log(beats)
</script>

以下是read.js的内容:

function read(filename){
    var fs = require('fs');
      var readline = require('readline');
      var stream = require('stream');

      var str =[]
      var instream = fs.createReadStream(filename);
      var outstream = new stream;
      var rl = readline.createInterface(instream, outstream);

      rl.on('line', function(line) {
        //console.log(line+'\n')
        str.push(line)
      });

      rl.on('close', function() {
        // do something on finish here
        console.log(str.length)
      });
      return str;
}

标签1:控制台中打印的值显示数组及其内容。

标签2:数组的长度显示为0。 有没有办法找到数组的大小?

  

控制台图像附在此处:

Console output

3 个答案:

答案 0 :(得分:0)

我想这是因为read()函数是异步的,完成执行需要一些时间。最初,长度打印为零然后是实际值5.尝试从read()函数返回一个promise并查看它是如何工作的。

 function async read(filename){
    var fs = require('fs');
      var readline = require('readline');
      var stream = require('stream');

      var str =[]
      var instream = fs.createReadStream(filename);
      var outstream = new stream;
      var rl = readline.createInterface(instream, outstream);

      rl.on('line', function(line) {
        //console.log(line+'\n')
        str.push(line)
      });

      rl.on('close', function() {
        // do something on finish here
        console.log(str.length)
      });
      return str;
}
    <script type="text/javascript" src="read.js"></script>
    <script>
      var beats=[]
      read('heartRate.txt').then(function(data){
        beats=data
        //do your stuff here
      })

    </script>

答案 1 :(得分:0)

不要工作,但

console.log(beats)           //label 1
console.log(beats.length)  

读取是异步发生的,推送只会在

之后执行
rl.on('line', function(line) {
        //console.log(line+'\n')
        str.push(line)
      });

在收盘时添加(rl.on('close',)。

答案 2 :(得分:0)

你应该让read返回一个承诺,只在数据加载完所有数据后才使用:

function read(filename){
  return new Promise((resolve, reject) => {
    const fs = require("fs");
    const readable = fs.createReadStream(filename);
    let data = [];
    readable.on('data', chunk => {
      data.push(chunk);
    });
    readable.on('end', () => {
      resolve(data);
    });
    readable.on('error', err => {
      reject(err);
    });
  }
}

你可以像这样使用它:

<script type="text/javascript" src="read.js"></script>
<script>
  read('heartRate.txt').
  then(beats => {
    console.log(beats)           //label 1
    console.log(beats.length)    //label 2
    for (i = 0; i < beats.length; i++) { 
      console.log(beats[i])
      if(parseInt(beats[i])>80 || parseInt(beats[i])<50){
       document.getElementById('Alert').innerHTML(`Abnormal heartrate of ${parseInt(beats[i])} beats`);
      }
    }
    console.log(beats)
  })
  .catch(err => console.log(`Oh no, an error has occurred: ${err} `));

</script>