You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在数组map函数内调用其他函数?提取YouTube地址报错解决

问题

作为前端新手,我从YouTube API获取了视频对象数组(结构示例如下),希望从每个对象的snippet.description字段中提取ADDRESS: 后的地址内容,并将地址作为属性添加到原对象中。

const videoArray = [{
  "kind": "youtube#playlistItem",
  "etag": "5_4yyrIK1DBbcLsSWOgtt5mHQrA",
  "id": "VVVjQWQ1TnA3Zk84U2VlakIxRlZLY1l3LnZmTGRHZGRHd093",
  "snippet": {
    "publishedAt": "2022-08-28T12:30:10Z",
    "channelId": "UCcAd5Np7fO8SeejB1FVKcYw",
    "title": "Central Vietnamese Street Food!! Noodles from Actual Heaven!!",
    "description": "🎥 SECOND CHANNEL!! MORE BEFRS »  \n👕 BEFRS MERCH » /ShopBEFRS\n💗 SUPPORT OUR MISSION » \n📷  CALVIN BUI’S IG » @fkndeliciousness | YouTube: https://youtube.com/c/FKNDeliciousness \n\nLike our music? Enjoy a free 30-day of Epidemic Sound for the best royalty-free music: http://share.epidemicsound.com/BEFRS \n- - - - - - - - - - - - - - - - -  \n1. TRADITIONAL CAO LAU NOODLE FACTORY \n\n🍜CAO LAU NOODLES: Soak the rice for 24 hours then grind it. Cook and stir until thick for 30 minutes.\nSteam for 30 minutes. Roll to make it flat and steam. \n- - - - - - - - - - - - - - - - -\n2. Quán Cao Lầu Bá Lễ\nADDRESS: 49/3 Trần Hưng Đạo, Sơn Phong, Hội An, Quảng Nam 56000\nOPENING TIME: 11AM - 8:30PM \n\n🍜CAO LAU: In a bowl, add herbs, bean sprouts, cao lau noodles, char siu, chả ram, deep fried pork fat (tốp mỡ) then meat sauce.\n\nPRICE: 35.000 VND / $1.51 USD \n- - - - - - - - - - - - - - - - -\n3. PHỞ SẮN FACTORY\n\n🍜 PHỞ SẮN: Grind the dried cassava into powder. Soak the cassava powder and water for 3 days and 3 nights then filter the water out, keeping the cassava powder. Whisk the cassava mixture in a pot for 30 minutes. Smooth mixture out. Place batter in a pressing machine. Dry noodles in the sun. After drying, cut into squares. \n- - - - - - - - - - - - - - - - -\n4. NHÀ HÀNG CỎ HỒNG\n\n🍜FRIED PHỞ SẮN: Pestle the pearl onions and place vegetables in hot water. Make the sauce with fish sauce, vinegar, msg, and coconut nectar. In a pan, add peanut oil. Fry the garlic, shrimp, and squid, add sugar, and then the vegetables. Add water and add a little starch. In another pan, deep-fry the pho san noodles. In a bowl, add the fried pho san, sauce, shrimp, squid, and top with spring onions.\n\n🍜PHỞ SẮN WITH FISH BROTH: Cook snakehead fish broth for 5 hours. Break the pho san into pieces and soak them in cold water for one minute. Place oil in a pot, add in pearl onions, garlic, tumeric, and the snakehead fish, and fry it for 10 minutes. Add in the pork. Pestle the fish. Add in the broth and cook\n- - - - - - - - - - - - - - - - -\n5. MÌ QUẢNG BÀ LÁNG\nADDRESS: Lê Thánh Tông street, An Phú ward, Tam Kỳ city, Quảng Nam Province\n\n🍜MÌ QUẢNG NOODLES: Soak the noodles and grind with a machine. Spread mixture on a flat surface and steam. When it’s cool, fold and cut it. \n\n🍜MÌ QUẢNG: Add fresh mì quảng in the bowl. Add char siu meat sauce. Add char siu and shrimp. Top with the peanuts and spring onions. Add herbs and fresh vegetables. \n\n#BEFRS #BestEverVietnamFoodTour #BestEverFoodReviewShow \n- - - - - - - - - - - - - - - - -\n💬COME SAY HI:\nINSTAGRAM »  (@besteverfoodreviewshow)\nFACEBOOK » \n \n💗SUPPORT OUR MISSION:\nPatreon is a platform that allows people to support creators on a recurring basis. Your contribution is an investment in the creative freedom of my channel and enables me to keep my content authentic and uninterrupted. Your donation allows me the time and resources to create more videos for you. We also have some pretty sweet rewards, exclusive to Patreon Bestys. » \n \nOur VIP Patrons: Susanne Smarr, Jim Klingsporn, Leo Lui, Sam Cassidy, Venetia Edmunds, Jack Murray, Eimile Nakoma, Jack Li, Stephen Balasta, Louis Chisari, Ryan Rhodes, Paul Citulski, Matthew Holden, David Baliles, Jackson Li, John Logan and Summer & Grayson Stumpf.  \n \n🥒 ABOUT BEFRS:\nHey, I’m Sonny! I’m from the US but I’ve been living in Asia for 10 years and started making food and travel videos to document my experiences. I travel to different parts of the world, hunting down and documenting the most unique food each country has to offer. \n \nIf you see any factual food errors in my videos, please feel free to politely let me know in the comments. I'm a huge fan of trying different, interesting foods in each country. My show is from a Western point of view, but more importantly, MY point of view. It is not meant to offend any person or culture. \n- - - - - - - - - - - - - - - - -\n🎬 CREDITS:\nHOST » Sonny Side\nDIRECTOR OF PHOTOGRAPHY » Nguyễn Tân Khải\nCAMERA OPERATOR » Tran Quang Dao\nVIDEO EDITOR » Thai Do \nCOLOR & MASTER » Quí Nguyễn\nPRODUCER » Nhi Huynh\n\nSelected tracks via Audio Network \nFor business inquiries: marketing@befrs.com",
    "channelTitle": "Best Ever Food Review Show",
    "playlistId": "UUcAd5Np7fO8SeejB1FVKcYw",
    "position": 0,
    "resourceId": { "kind": "youtube#video", "videoId": "vfLdGddGwOw" },
    "videoOwnerChannelTitle": "Best Ever Food Review Show",
    "videoOwnerChannelId": "UCcAd5Np7fO8SeejB1FVKcYw"
  },
  "contentDetails": { "videoId": "vfLdGddGwOw", "videoPublishedAt": "2022-08-28T12:30:10Z" }
}, {... other similar object}]

我编写了如下代码,但运行时出现element.map is not a function错误:

let splitAddressResult = [];let removeNoiseResult = [];let extractAddressResult = [];

const splitAddress = (video) => {    splitAddressResult = video.snippet.description.split("ADDRESS: ");};
  
const removeNoise = (array) => {    removeNoiseResult = array.map((element) => element.slice(1));};
  
const extractAddress = (array) => {    array.map((element) =>      element.map((arr) => extractAddressResult = arr.split("\n")[0])    );    return extractAddressResult;};

const getAdress = (videoList) => {  videoList.map(function(video) {    splitAddress(video);    removeNoise(splitAddressResult);    extractAddress(removeNoiseResult);    video.push({address: extractAddressResult});  });};

getAddress(videoArray);

问题分析与修复方案

错误原因

  1. element.map is not a function:extractAddress函数中,array是字符串拆分后的数组,每个element是字符串类型,而字符串没有map方法,错误地对字符串调用map导致报错。
  2. 全局变量污染:使用全局变量存储中间结果,处理多个视频时会出现数据混乱。
  3. 对象操作错误:video是对象而非数组,不能用push方法添加属性,应直接赋值video.address = ...。
  4. 函数名拼写错误:getAdress少写了一个d,调用时用的getAddress会导致函数未定义。

修复后的代码

推荐用正则表达式提取地址,更简洁可靠,还能处理多个地址的场景:

const extractAddresses = (videoList) => {
  // 匹配"ADDRESS: "开头到换行符的内容
  const addressRegex = /ADDRESS: (.*?)\n/g;
  videoList.forEach(video => {
    const description = video.snippet.description;
    const addresses = [];
    let match;
    // 提取所有匹配的地址
    while ((match = addressRegex.exec(description)) !== null) {
      addresses.push(match[1].trim());
    }
    // 单个地址存字符串,多个存数组
    video.address = addresses.length === 1 ? addresses[0] : addresses;
  });
};

// 调用函数
extractAddresses(videoArray);

如果坚持用拆分方式,修正后的代码如下:

const getAddress = (videoList) => {
  videoList.forEach(video => {
    const parts = video.snippet.description.split("ADDRESS: ");
    const addresses = [];
    // 从第二个元素开始处理(第一个是ADDRESS之前的内容)
    for (let i = 1; i < parts.length; i++) {
      const address = parts[i].split("\n")[0].trim();
      addresses.push(address);
    }
    video.address = addresses.length === 1 ? addresses[0] : addresses;
  });
};

getAddress(videoArray);

说明

  • 两种方式都支持提取多个地址,贴合实际场景。
  • 用forEach遍历数组(map会返回新数组,修改原对象用forEach更合适)。
  • 移除全局变量,每个视频的处理独立,避免数据冲突。
  • 直接给对象添加address属性,纠正了push的错误用法。

内容的提问来源于stack exchange,提问作者Dimas Rizqi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:15:30