我想获取数组中每个元素的长度
我的代码是
var a = "Hello world" ;
var chars = a.split(' ');
所以我将有一个数组
chars = ['Hello' , 'world'] ;
但是我如何获得每个单词的长度?
Hello = 5
world = 5
您可以使用地图数组功能:
var lengths = chars.map(function(word){
return word.length
})
您可以创建一个结果对象(因此您拥有键“ hello”,长度为5):
function getLengthOfWords(str) {
var results = {};
var chars = str.split(' ');
chars.forEach(function(item) {
results[item] = item.length;
});
return results;
}
getLengthOfWords("Hello world"); // {'hello': 5, 'world': 5}
这里的关键是使用字符串的.length属性:
for (var i=0;i<chars.length;i++){
console.log(chars[i].length);
}
尝试map()
var words = ['Hello', 'world'];
var lengths = words.map(function(word) {
return word + ' = ' + word.length;
});
console.log(lengths);
ES6现在已经广泛可用(2019-10-03),为完整起见,您可以将arrow operator与.map()
结合使用
var words = [ "Hello", "World", "I", "am", "here" ];
words.map(w => w.length);
> Array [ 5, 5, 1, 2, 4 ]
或者非常简洁
"Hello World I am here".split(' ').map(w => w.length)
> Array [ 5, 5, 1, 2, 4 ]
您可以使用forEach,如果您想保留单词和长度,可以这样操作:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push([str, str.length]);
});
然后您可以访问数组中的大小和单词。
可选地,您可以有一个POJO对象,以便于访问:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push({word: str, length: str.length});
});
然后您可以像这样访问它们:
console.log(words[0].length); //5
console.log(words[0].word); //"Hello"
或使用map获得相同的POJO:
var words = chars.map(function(str) {
return {word: str, length: str.length};
});