2017-04-10 24 views
0

我的問題轉化爲重點,重視對

  1. 如何ROM的讀取TXT文件中的JS
  2. 來處理數據最好的辦法。像這樣或下面的東西?

    var data = [ 
    { 
        name: "Orange", 
        type: "Fruit", 
        desc: "some description about the recipe" 
    }, 
        { 
        name: "Spinach", 
        type: "Veg", 
        desc: "some description about the recipe" 
    }, 
        { 
        name: "Beans", 
        type: "Veg", 
        desc: "some description about the recipe" 
    }, 
    

    ]

我想有一個對象數組,這樣我可以進一步處理它打印出來的水果獨特的名字,只是蔬菜和水果正好。

回答

1

您可以使用AJAX和正則表達式完成此操作。

如果你正在使用jQuery:

$.ajax({ 
    url: 'someTextFile.txt', 
    success: function(data) { 
     var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n \t]*([a-zA-Z0-9 \.]+)/g, 
      recipe, allRecipies = []; 
     while (recipe = rege.exec(data)) { 
      allRecipies.push({ 
       name: recipe[1], 
       type: recipe[2], 
       desc: recipe[3], 
      }); 
     } 
     console.log(allRecipies); 
    } 
}); 

如果你不使用jQuery

var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     data = xhttp.responseText; 
     var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n \t]*([a-zA-Z0-9 \.]+)/g, 
      recipe, allRecipies = []; 
     while (recipe = rege.exec(data)) { 
      allRecipies.push({ 
       name: recipe[1], 
       type: recipe[2], 
       desc: recipe[3], 
      }); 
     } 
     console.log(allRecipies); 
    } 
}; 
xhttp.open("GET", "filename", true); 
xhttp.send(); 
0

要不要打擾創建自己的解析器的格式閱讀。

保存在一個標準的數據交換格式像jsonxml

有這麼多的人,並查找標準庫來分析他們,讓您的信息內容。

我會推薦json,因爲Javascript是一個解析JSON文件的JSON對象。他們是解析JSON的其他優秀庫。

+0

你能指給我一個嗎? –

+0

你是否正在節點上運行,如果是的話..節點作爲本機JSON.parse ..試試。 –

+0

我只是試圖在香草JS –