如何更简洁地表达这个Javascript?

时间:2012-01-23 04:53:32

标签: javascript python

我有一些Python代码,我正在移植到Javascript:

word_groups = defaultdict(set)
for sentence in sentences:
    sentence.tokens = stemmed_words(sentence.str_)
    for token in sentence.tokens:
        word_groups[sentence.actual_val].add(token)

我对Javascript知之甚少,所以这是我能做的最好的事情:

var word_groups = {}
for(var isent = 0; isent < sentences.length; isent++) {
    var sentence = sentences[isent]
    sentence.tokens = stemmed_words(sentence.str_)
    for(var itoken = 0; itoken < sentence.tokens.length; itoken++) {
        var token = sentence.tokens[itoken]
        if(!(sentence.actual_val in word_groups))
            word_groups[sentence.actual_val] = []
        var group = word_groups[sentence.actual_val]
        if(!(token in group))
            group.push(token)
    }
}

有人可以建议让javascript代码看起来更像python的方法吗?

3 个答案:

答案 0 :(得分:1)

我很可能误解了你的Python代码所做的事情,但假设你在字数之后,我会按如下方式编写:

var word_groups = {}
sentences.forEach(function (sentence) {
  sentence.tokens = stemmed_words(sentence.str_)
  sentence.tokens.forEach(function (token) {
    var val = sentence.actual_val
    word_groups[val] = (word_groups[val] || 0) + 1
  })
})

如果输入中出现“构造函数”一词,则上述操作将失败。可以解决这个JavaScript怪癖:

var word_groups = {}
sentences.forEach(function (sentence) {
  sentence.tokens = stemmed_words(sentence.str_)
  sentence.tokens.forEach(function (token) {
    var val = sentence.actual_val
    if (!word_groups.hasOwnProperty(val)) word_groups[val] = 0
    word_groups[val] += 1
  })
})

答案 1 :(得分:1)

我将假设如果您使用的forEach可用的环境,reduceObject.keys也可用。 (例如ECMAScript&gt; = 1.8.5):

var word_groups = sentences.reduce(function (groups, sentence) {
  var val = sentence.actual_val
  var group = groups[val] = groups[val] || []
  stemmed_words(sentence.str_).forEach(function (t) {
    if (!(t in group)) group.push(t)
  })
  return groups
}, {})

答案 2 :(得分:0)

如果你肯定不是Javascript 1.6或更高版本(值得注意的是IE 8有Javascript 1.5),你可能需要jQuery作为兼容层。例如$ .each(a,f)与a.forEach(f)兼容。

相关问题