编程语言
首页 > 编程语言> > javascript-如何使用Map对象查找数组的元素数

javascript-如何使用Map对象查找数组的元素数

作者:互联网

我有一个单词的段落,想查找每个单词的计数,特别是使用JavaScript的Map对象.

我知道可以使用.get()和.set()方法来实现,但是我不确定如何实现.

下面是我的代码.

let paragraph = `Lorem ipsum donec nisi taciti et elit congue turpis, lobortis 
                 massa suscipit massa est a praesent metus egestas, conubia turpis 
                 in cursus libero pharetra praesent.
                 Per bibendum taciti sit taciti facilisis a bibendum nisl massa non 
                 aliquam sem auctor ipsum eros, massa sed cubilia porta primis 
                 felis elementum non fringilla conubia neque aenean urna.`

// Split the paragraph into an array of individual words.

let words = paragraph.match(/\w+/gi);

let map = new Map();

for (let i = 0; i < words.length; i++) {
  let word = words[i];
  map.set(word, 0);
  // Logic - if (map contains word) {
    map.set(word, count += 1);
  } else {
    map.set(word, 1);
  }
}

console.log(map);

解决方法:

在地图上使用Array#reduce.

对于每次迭代,请在地图中设置单词.

a.get(“ Lorem”)将返回一个数字或未定义. ||处理是否未定义.然后加1.

Map#set还返回地图对象.

const paragraph = `Lorem ipsum donec nisi taciti et elit congue turpis, lobortis massa suscipit massa est a praesent metus egestas, conubia turpis in cursus libero pharetra praesent.
Per bibendum taciti sit taciti facilisis a bibendum nisl massa non aliquam sem auctor ipsum eros, massa sed cubilia porta primis felis elementum non fringilla conubia neque aenean urna.`

const words = paragraph.match(/\w+/gi);

const res = words.reduce((a,c)=>{
  return a.set(c, (a.get(c)||0) + 1);
}, new Map());

console.log([...res]);

标签:javascript-objects,javascript
来源: https://codeday.me/bug/20191108/2006940.html