在循环外访问javascript变量



如何将John, Liza, Peter移出for循环?

var siblings = ["John", "Liza", "Peter"];
    for (var i=0; i < siblings.length; i++) {
      names = siblings[i];
      console.log(names) // correctly outputs John, Liza, Peter     
    }
console.log(names) // only gives Peter

更新:我试图在单元测试用例中重现问题。但这是全部。

我做了一个请求,得到了一个数组

[ { kind: 'youtube#video',
    etag: '"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/XDKLx9FZygpwjYlzaTU-HAH31tw"',
    id: 'b4Bj7Zb-YD4',
    snippet:
     { publishedAt: '2016-10-28T07:00:01.000Z',
       channelId: 'UCaHNFIob5Ixv74f5on3lvIw',
       title: 'Calvin Harris - My Way (Official Video)',
       description: 'Calvin Harris - My Way (Official Video)nDownload My Way:  http://smarturl.it/CHMyWay?IQid=ytnListen to My Way: http://smarturl.it/StreamCH?IQid=ytnn---------nnFollow Calvin Harris:nFacebook: https://www.facebook.com/calvinharris/ nTwitter: https://twitter.com/CalvinHarris nInstagram: https://www.instagram.com/calvinharris/ nWebsite: http://calvinharris.com/ nn---------nnCalvin Harris - My Way (Lyrics)nnWhy wait nTo saynAt least I did it my way nLie awake nTwo faced nBut in my heart I understand nI made nMy move nAnd it was all about you nNow I feel nSo far removed nnYou were the one thing in my way nnMy waynAway away away',
       thumbnails: [Object],
       channelTitle: 'CalvinHarrisVEVO',
       tags: [Object],
       categoryId: '10',
       liveBroadcastContent: 'none',
       localized: [Object] },
    statistics:
     { viewCount: '8313145',
       likeCount: '271119',
       dislikeCount: '7364',
       favoriteCount: '0' } },
  { kind: 'youtube#video',
    etag: '"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/c2pD6DG-ieqcYFEcGjGB31NYRKk"',
    id: '0zGcUoRlhmw',
    snippet:
     { publishedAt: '2016-10-24T14:00:01.000Z',
       channelId: 'UCRzzwLpLiUNIs6YOPe33eMg',
       title: 'The Chainsmokers - Closer ft. Halsey',
       description: 'Collage EP: nPre-order on Amazon: http://smarturl.it/CollageAmznUrban Outfitters White Vinyl:  http://smarturl.it/CollageVinylnn"Closer" ft. HalseyniTunes: http://smarturl.it/CloseriTnSpotify: http://smarturl.it/CloserStreamnApple Music: http://smarturl.it/CloserAMnAmazon: http://smarturl.it/CloserAmznnDirected by: Dano CernynnFollow The Chainsmokers:nhttp://www.youtube.com/thechainsmokersnhttp://www.twitter.com/thechainsmokersnhttp://www.facebook.com/thechainsmokersnhttp://www.instagram.com/thechainsmokersnhttp://www.soundcloud.com/thechainsmokersnnFollow Halsey:nTwitter: http://twitter.com/halseynFacebook: https://www.facebook.com/HalseyMusicnInstagram: http://instagram.com/iamhalseynSpotify: http://smarturl.it/HalseySpotifynNewsletter: http://www.iamhalsey.com/mailinglistnPurchase Music: http://www.iamhalsey.com/badlandsbox',
       thumbnails: [Object],
       channelTitle: 'ChainsmokersVEVO',
       tags: [Object],
       categoryId: '10',
       liveBroadcastContent: 'none',
       localized: [Object] },
    statistics:
     { viewCount: '21315027',
       likeCount: '573642',
       dislikeCount: '19913',
       favoriteCount: '0',
       commentCount: '40899' } } 
]

所以我把它放在一个变量中,比如sibling。然后循环遍历整个数组,得到snippet。标题、snippet.publishedAt。到目前为止一切都很好。但是我想把它推入一个新的数组,并使它可以在循环外使用。

我现在的代码:

listVideos是我之前粘贴的块。

listVideos.forEach(function list(item) {
    data = new Array();
    title = item.snippet.title; 
    return data.push(title);
    });
console.log(data); // only gives first title. I want to get all titles in an array stored inside data. And make data available globally

在开始时设置变量var data对我来说不起作用,因为我在forEach循环之外有其他函数。因此,它必须是一种灵活的方式,我可以移动到任何我想要的地方,比如某种函数作用域。

谢谢。

它只说Peter,因为每次循环迭代都将'names'设置为特定的名称。如果你想获得所有的名字,那么'names'必须是一个数组,并且你应该在循环期间将名字推入:

names.push(siblings[i])
var names = new Array();
names.push(siblings[i]);
console.log(names);

你不需要loop:

var siblings = ["John", "Liza", "Peter"];
var str = siblings.join(',');
console.log(str); //John,Liza,Peter

相关内容

  • 没有找到相关文章

最新更新