Get length of every element in array - JavaScript

2020-07-13 08:22发布

I want to get length of every element in array

my code is

var a = "Hello world" ; 
var chars = a.split(' '); 

so I will have an array of

chars = ['Hello' , 'world'] ; 

but how I can get length of each word like this ?

Hello = 5 
world = 5

6条回答
smile是对你的礼貌
2楼-- · 2020-07-13 08:42

You can use map Array function:

var lengths = chars.map(function(word){
 return word.length
}) 
查看更多
【Aperson】
3楼-- · 2020-07-13 08:48

Try map()

var words = ['Hello', 'world'];

var lengths = words.map(function(word) {
  return word + ' = ' + word.length;
});

console.log(lengths);

查看更多
乱世女痞
4楼-- · 2020-07-13 08:50

You can use forEach, if you want to keep the words, and the length you can do it like this:

var a = "Hello world" ; 
var chars = a.split(' ');

    var words = [];
    chars.forEach(function(str) { 
        words.push([str, str.length]);
    });

You can then access both the size and the word in the array.

Optionally you could have a little POJO object, for easier access:

var a = "Hello world" ; 
var chars = a.split(' ');

var words = [];
chars.forEach(function(str) { 
    words.push({word: str, length: str.length});
});

Then you can access them like:

console.log(words[0].length); //5
console.log(words[0].word); //"Hello"

Or using map to get the same POJO:

var words = chars.map(function(str) { 
    return {word: str, length: str.length};
});
查看更多
走好不送
5楼-- · 2020-07-13 08:52

You could create a results object (so you have the key, "hello", and the length, 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}
查看更多
该账号已被封号
6楼-- · 2020-07-13 08:57

The key here is to use .length property of a string:

   for (var i=0;i<chars.length;i++){
    console.log(chars[i].length);
    }
查看更多
爷、活的狠高调
7楼-- · 2020-07-13 08:58

ES6 is now widely available (2019-10-03) so for completeness — you can use the arrow operator with .map()

var words = [ "Hello", "World", "I", "am", "here" ];
words.map(w => w.length);
> Array [ 5, 5, 1, 2, 4 ]

or, very succinctly

"Hello World I am here".split(' ').map(w => w.length)
> Array [ 5, 5, 1, 2, 4 ]
查看更多
登录 后发表回答