【发布时间】:2016-03-29 16:31:04
【问题描述】:
我的问题是可以改变和排列成一个对象吗?
以下代码计算数组中每个单词的出现次数。
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
changedString = string.replace(/,/g, " "), // remove the array elements
split = changedString.split(" "), // split the string
words = [];
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
是否可以改变它,而不是像这样返回一个数组:
[ Not: 1,
long: 1,
left: 2,
grab: 1,
an: 4,
Easter: 5,
bargain: 1,]
而是返回一个像这样的对象? { word: 'Not' num: 1 }等
【问题讨论】:
-
您可以使用括号表示法分配对象属性。
var obj = {};然后点符号添加属性obj.prop1 = 2;或括号符号,如obj["prop2"] = 2;方便的是括号符号可以使用字符串,因此var propName = "prop3"然后obj[propName] = 2;将obj.prop3 === 2设为 true。 -
我想你真正想要的是一个对象数组:[ { word: 'Not', num: 1 }, { word: 'long', num: 1 }, ... ] 而不是而不是单个对象。
-
@Andy tweetext is and array that then变成一个可以排序的字符串
-
@Arnauld 如果我可以按对象的 num 元素对该数组进行排序,那么可以。
-
@cockmagic,你能显示初始
tweetxt值吗?
标签: javascript arrays object javascript-objects