第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

循環(huán)由于某種原因被卡住,然后最終返回未定義

循環(huán)由于某種原因被卡住,然后最終返回未定義

萬(wàn)千封印 2022-09-23 09:42:06
這就是我試圖解決的問(wèn)題:給定:一個(gè)包含名稱(chēng)哈希的數(shù)組Return:格式為用逗號(hào)分隔的名稱(chēng)列表的字符串,但最后兩個(gè)名稱(chēng)除外,最后兩個(gè)名稱(chēng)應(yīng)以 & 符號(hào)分隔。例:list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])// returns 'Bart, Lisa & Maggie'list([ {name: 'Bart'}, {name: 'Lisa'} ])// returns 'Bart & Lisa'list([ {name: 'Bart'} ])// returns 'Bart'list([])// returns ''注意:所有哈希值都經(jīng)過(guò)預(yù)先驗(yàn)證,并且僅包含 A-Z、a-z、“-”和 “。這是我的代碼:var finalName;var notFinal;function list(names){  var finalNames = names.forEach(returnNames);        console.log(typeof finalNames);  function returnNames() {    for (var i = 0; i<names.length; i++) {      var nameValue = Object.keys(names[i]).map(key => names[i][key])    }  }  for(var i = 0; i<finalNames.length; i++) {    if (finalNames.length / i == 1) {      finalName = "& " + finalNames[i];     }    else {      notFinal = finalNames[i] + ", ";    }  }  console.log(notFinal + finalName);}list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])它卡在循環(huán)中,最后給出一個(gè)錯(cuò)誤:TypeError: Cannot read property 'length' of undefined    at list    at /home/codewarrior/index.js:30:1    at Object.handleError        <anonymous>如何修復(fù)此問(wèn)題?
查看完整描述

2 回答

?
搖曳的薔薇

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊

這是因?yàn)?forEach 不會(huì)返回任何內(nèi)容,請(qǐng)嘗試改用映射函數(shù)。

var finalNames = names.map(returnNames);


查看完整回答
反對(duì) 回復(fù) 2022-09-23
?
滄海一幻覺(jué)

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊

正如他們已經(jīng)指出的那樣,返回 。相反,您可以使用此來(lái)修改您的函數(shù)Array.prototype.forEachundefined.mapreturnNames


var finalName;

var notFinal;


function list(names){

  // Changed .forEach with .map

  var finalNames = names.map(returnNames);

  console.log(typeof finalNames);


  function returnNames(person) {

    // If you only need to get the object values, use Object.values instead of Object.keys

    return Object.values(person);

  }


  for(var i = 0; i < finalNames.length; i++) {

    // Added + 1 because i could never be equal to the array length

    // Note that you'll need to make 1 or 2 more changes before this code works as expected

    if (finalNames.length / (i + 1) == 1) {

      finalName = "& " + finalNames[i]; 

    }

    else {

      notFinal = finalNames[i] + ", ";

    }

  }


  console.log(notFinal + finalName);

}


list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])


查看完整回答
反對(duì) 回復(fù) 2022-09-23
  • 2 回答
  • 0 關(guān)注
  • 124 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)