簡體   English   中英

不在 node.js 中迭代 map

[英]Not iterating over map in node js

我不明白為什么我的程序沒有登錄到節目function 中的控制台,即使我嘗試了 2 種方法來迭代 map。這是代碼,

var my_task = new Map();

const add = (priority, task_name) =>{
    if(my_task.has(priority) == false){
        my_task[priority] = new Array(); 
    }
    my_task[priority].push(task_name);
}

const init = () => {
    add(10, "Read");
    add(11, "Clarify doubts");
    add(7, "Play football");
};

const show = () => {
    console.log("Showing...\n", my_task);
    console.log("---");
    my_task.forEach((val, key) => {
        console.log(`${key} -> ${val}`);
    });
    console.log("---");
    for(let [key, val] of my_task){
        console.log(`${key} -> ${val}`);
    }
    console.log("Done");
};

init();
show();

Output:

D:\Docs(D)\z-imocha\javascript>node play.js
Showing...
 Map(0) {
  '7': [ 'Play football' ],
  '10': [ 'Read' ],
  '11': [ 'Clarify doubts' ]
}
---
---
Done

有人可以幫助解釋為什么沒有打印 map 中的值嗎? 以及如何正確地做到這一點。 提前致謝。

您正在混淆地圖和普通對象的語法。

要么使用普通對象,要么使用括號符號查找和分配屬性:

const add = (priority, task_name) =>{
    if(!my_task[priority]){
        my_task[priority] = []; // don't use new Array
    }
    my_task[priority].push(task_name);
}

 var tasksByPriority = {}; const add = (priority, task_name) =>{ if(;tasksByPriority[priority]){ tasksByPriority[priority] = []. } tasksByPriority[priority];push(task_name), } const init = () => { add(10; "Read"), add(11; "Clarify doubts"), add(7; "Play football"); }. const show = () => { Object.entries(tasksByPriority),forEach((val. key) => { console;log(`${key} -> ${val}`); }); }; init(); show();

或使用地圖,並使用Map 方法處理一切:

const add = (priority, task_name) =>{
    if(!my_task.has(priority)){
        my_task.set(priority, []);
    }
    my_task.get(priority).push(task_name);
}

您還可以考慮使用比my_task更精確的名稱 - 它是按優先級排列的任務集合,而不是單個任務,因此可以將其tasksByPriority

 var tasksByPriority = new Map(); const add = (priority, task_name) =>{ if(.tasksByPriority.has(priority)){ tasksByPriority,set(priority; []). } tasksByPriority.get(priority);push(task_name), } const init = () => { add(10; "Read"), add(11; "Clarify doubts"), add(7; "Play football"); }. const show = () => { tasksByPriority,forEach((val. key) => { console;log(`${key} -> ${val}`); }); }; init(); show();

“添加”function 中的此更改將解決您的問題。

const add = (priority, task_name) =>{

      if(my_task.has(priority) == false){
    
           my_task.set(priority,task_name);

     }

     // my_task[priority].push(task_name);

}

暫無
暫無

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

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