簡體   English   中英

Javascript-在foreach函數中切換數組名稱

[英]Javascript - Switching array name in foreach function

試圖使其盡可能簡單易懂...

我有一個JS函數,該函數本質上是選擇一個人選擇的數組(列表),然后將其傳遞給另一個函數,以打印出該數組。 問題是我不知道如何使用已通過的數組名稱來看看:

數組:

var allLists =['list1', 'list2'];
var list1 = ['orange', 'pear', 'apple'];
var list2 = ['car', 'plane', 'bike'];

遍歷列表的功能:

function printAllLists() {
    lists.forEach(function(entry) {
        count++;
        document.write("<h2> List Number " + count + "</h2>");
        printList(entry);

    });
}

將每個列表內容輸出到表的功能

function printList(listname) {
    document.write("<table>");
    document.write("List Name Is: " + listname);

    listname.forEach(function(entry) {  //HERE IS THE PROBLEM   
        document.write("<tr><td>");
        document.write(entry);
        document.write("</td></tr>");   
    });
    document.write("</table>");
}

我的問題是,下面的行從字面上使用“ listname”,而不是作為“ list1”或“ list 2”傳遞的列表名稱

listname.forEach(function(entry) {

因此,它只會因此錯誤而失敗。 我如何獲取它來交換數組名稱。 抱歉,如果我不太清楚我要說的是什么,我不確定該如何准確地寫出這句話(這可能就是Google無法提供幫助的原因。)

Uncaught TypeError: listname.forEach is not a function

JSFiddle鏈接到JSFiddle- https: //jsfiddle.net/38x5nw62/謝謝

像這樣做:

var list1 = ['car', 'plane', 'bike'];
var list2 = ['car', 'plane', 'bike'];
var allLists = [list1, list2];

此處的工作代碼: https : //jsfiddle.net/38x5nw62/1/

您在哪里使用var allLists = ['list1', 'list2']; wich只包含字符串'list1''list2' ,而不包含字符串唯一命名的變量/數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM