JavaScript数组不返回数字

时间:2017-05-06 10:16:09

标签: javascript html

当我在下面的示例中使用数字时,我得到正确的返回/输出。

var array = [1,2,4,5,];
divBy2 = v => v / 2;
var result = array.map(divBy2);

当我在下面尝试这个时,我会得到NaV。

var array = [output];
divBy2 = v => v / 2;
var result = array.map(divBy2);

我的代码编写如下。基本上,我正在加载一个包含以下行的文本文件:

Numbers (999.000,999.000),(999.000,999.000),  

然后我想创建一个数组并取这些数字并除以2.只返回没有整个字符串的数字。

var reader = new FileReader();

function readText(that){

        if(that.files && that.files[0]){
            var reader = new FileReader();
            reader.onload = function (e) {  
                var output=e.target.result;


output=output.split("\n").filter(/./.test,/Numbers/).join("\n").replace(/[^0-9.,]/g,'');

var array = [output];
divBy2 = v => v / 2;
var result = array.map(divBy2);

document.getElementById('inputTextToSave').innerHTML= output;

1 个答案:

答案 0 :(得分:1)

  1. 您不能在数组中放置字符串以使逗号分隔的语法工作,而是创建一个包含单个字符串("1,2,3")的数组。
  2. 
    
    let output = "1,2,3";
    var array = [output];//doesnt  work
    //this creates  ["1,2,3"]
    //array[0] === "1,2,3"
    console.log("array", array);
    
    var array2 = output.split(",");//works but creates string array
    //this creates  ["1","2","3"]
    //array2[0] === "1"
    //array2[1] === "2"
    //array2[2] === "3"
    console.log("array2", array2)
    
    var array3 = output.split(",").map(Number);//works and converts to number
    //this creates  [1,2,3]
    //array2[0] === 1
    //array2[1] === 2
    //array2[2] === 3
    console.log("array3", array3)
    
    //The closest to your attemp is eval() which shouldnt be used in normal cases
    var array4 = eval("[" + output + "]");
    console.log(array4)
    
    
    

    1. output是代码中的逗号分隔字符串(999.000,999.000,999.000,999.000,999.000,999.000,999.000,999.000,999.000),使用String.prototype,split将其拆分为数组
    2. 
      
      let output = `Numbers (999.000,999.000),(999.000,999.000),
      Numbers (999.000,999.000),(999.000,999.000),
      Numbers (999.000,999.000),(999.000,999.000),
      Numbers (999.000,999.000),(999.000,999.000)`;
      
      output=output.split("\n").filter(/./.test,/Numbers/).join("\n").replace(/[^0-9.,]/g,'');
      console.log(output);
      let array = output.split(",");
      console.log(array);
      let divBy2 = v => v / 2;
      let result = array.map(divBy2);
         console.log(result);
      
      
      

      要查看您的代码:

      
      
      let output = "1, 2, 3";
      var array = [output];
      console.log(array);//["1,2,3"]
      divBy2 = v => v / 2;
      var result = array.map(divBy2);
      console.log(result);//[NaN]  as "1,2,3"/2 =NaN (not a number)