将数组更改为对象
Changing an array to an object
我的问题是可以将数组更改为对象吗?
以下代码计算数组中每个单词的出现次数。
// 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,]
而是 returns 这样的对象? { word: 'Not' num: 1 }
等
您可以使用 Object.key()
and Array#map()
将对象转换为对象数组。
var obj = { Not: 1, long: 1, left: 2, grab: 1, an: 4, Easter: 5, bargain: 1 },
array = Object.keys(obj).map(function (k) { return { word: k, num: obj[k] }; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
// edit sorting
array.sort(function (a, b) { return a.num - b.num; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
我的问题是可以将数组更改为对象吗?
以下代码计算数组中每个单词的出现次数。
// 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,]
而是 returns 这样的对象? { word: 'Not' num: 1 }
等
您可以使用 Object.key()
and Array#map()
将对象转换为对象数组。
var obj = { Not: 1, long: 1, left: 2, grab: 1, an: 4, Easter: 5, bargain: 1 },
array = Object.keys(obj).map(function (k) { return { word: k, num: obj[k] }; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
// edit sorting
array.sort(function (a, b) { return a.num - b.num; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');