2017-09-04 135 views
1

我使用的是YouTube搜索庫獲取JavaScript對象

search(searchTerm, opts, function(err, results) { 
      if (err) return console.log(err); 

      console.dir(results); 
     }); 

,它返回一個JS對象與第一視頻發現這樣

[ { id: 'xsPHeH-pNQU', 
link: 'https://www.youtube.com/watch?v=xsPHeH-pNQU', 
kind: 'youtube#video', 
publishedAt: '2015-04-10T19:36:16.000Z', 
channelId: 'UC9EZGiMrK8-OYbLH3Yfj_QQ', 
channelTitle: 'IQ Tests | Personality Tests | Funny Test Videos', 
title: '✔ Which Nickname is Perfect For You? (Personality Test)', 
description: 'What nickname fits you best? What is your cute nickname? What is your best nickname? What should your nickname be? Be my friend on Facebook ...', 
thumbnails: { default: [Object], medium: [Object], high: [Object] } } ] 

我試圖提取路段出了這通過使用

var videoUrl = results.link; 

var videoUrl = results["link"]; 

但每次我得到它登錄到控制檯什麼videoUrl是,它一直說未定義。完整的代碼看起來像這樣

var searchTerm = message.content.slice(8, 2000); 
     search(searchTerm, opts, function(err, results) { 
      if (err) return console.log(err); 
      var videoUrl = results.link; 
      console.dir(results); 
      console.log(videoUrl); 
      message.channel.send(videoUrl); 
     }); 

任何想法我做錯了什麼?

回答

0

該對象位於數組中,因此您需要引用數組中的項目。因爲它是陣列中的第一個項目,所以需要使用[0]

var videoUrl = results[0].link;