JavaScript - 遍历数组并替换页面上的单词

时间:2016-04-16 01:19:34

标签: javascript arrays dom

我有一个名为“words”的数组,其结构如下:

Object {text: "house", frequency: 220}
Object {text: "wow", frequency: 193}
Object {text: "language", frequency: 164}
Object {text: "cars", frequency: 73}
Object {text: "computer", frequency: 46}
Object {text: "plane", frequency: 38}
Object {text: "maple", frequency: 35}
Object {text: "tree", frequency: 32}
Object {text: "door", frequency: 30}
Object {text: "carpet", frequency: 27}
Object {text: "windows", frequency: 26}
Object {text: "floor", frequency: 25}
Object {text: "roof", frequency: 22}
Object {text: "ceiling", frequency: 21}
Object {text: "barge", frequency: 21}
Object {text: "wave", frequency: 20}
Object {text: "example", frequency: 20}
Object {text: "boat", frequency: 20}
Object {text: "ear", frequency: 20}
Object {text: "sky", frequency: 19}
Object {text: "chin", frequency: 18}
Object {text: "mashed", frequency: 18}
Object {text: "broke", frequency: 18}
Object {text: "impossible", frequency: 18}
Object {text: "well", frequency: 18}

我需要遍历整个数组,将text:参数中的每个单词替换为当前网页上的频率值。

使用上面数组中的数据的示例:

一个空白网页,只是说:

Wow, I can't believe the computer she had! It was loud enough to shake the house!

运行脚本后,页面会说:

193, I can't believe the 46 she had! It was loud enough to shake the 220!

我理解如何访问数组中的每个元素,但我不知道如何获取参数以在当前页面上定位单词,然后如何获取第二个参数以用作替换。

words.forEach(function(bla) { console.log(bla); });

谢谢!

3 个答案:

答案 0 :(得分:0)

这里你的评论是如何从数组中获取相关属性:

JSBin example with logging

var a = [{text: "house", frequency: 220},
 {text: "wow", frequency: 193},
 {text: "language", frequency: 164}];

for (var i = 0; i < a.length; i++) {
  // use a for loop to loop through the array
  // now grab each item:
  var item = a[i];
  // grab the text:
  var text = item.text;
  var frequency = item.frequency;

  console.log(text, frequency);
}

答案 1 :(得分:0)

首先将对象数组转换为格式为{ wow: 193 }的对象。这使搜索/替换更容易。

var obj = arr.reduce(function(p, c) {
  p[c.text] = c.frequency;
  return p;
}, {});

(基于我的演示)抓取你的文本,并将其拆分成一个数组,并指定一个输出元素。

var txtArr = document.getElementById('body').textContent.split(' ');
var out = document.getElementById('out');

处理文字。对于每个word匹配没有无关标点符号的字母,如果它与对象键匹配,则返回替换的字符串,否则返回该字。最后join处理过的单词数组。

var processed = txtArr.map(function (word) {
  var w = word.match(/[a-zA-Z]+/g)[0];
  var temp = w.toLowerCase();
  if (obj[temp]) return word.replace(w, obj[temp]);
  return word;
}).join(' ');

然后只需将处理过的内容添加到输出元素。

out.textContent = processed;

DEMO

答案 2 :(得分:0)

// Using Loadash 
SIMPLE    
var hash = _.zipObject(_.map(arrayOfWords, 'text'), _.map(arrayOfWords, 'frequency'));
var outputString = _.map(_.words(sentence), function (word) {return b[word.toLowerCase()] || word})

// Here Hash is the key value of text and frequency.
// The sentence is just the string sentence.