获取数组中每个元素的长度 - JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33399786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:26:36  来源:igfitidea点击:

Get length of every element in array - JavaScript

javascriptarrays

提问by HyperScripts

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

采纳答案by juvian

You can use map Array function:

您可以使用 map Array 函数:

var lengths = chars.map(function(word){
 return word.length
}) 

回答by nils

You could create a results object (so you have the key, "hello", and the length, 5):

您可以创建一个结果对象(因此您有键“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}

回答by uksz

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

这里的关键是使用字符串的 .length 属性:

   for (var i=0;i<chars.length;i++){
    console.log(chars[i].length);
    }

回答by AmmarCSE

Try map()

尝试地图()

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

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

console.log(lengths);

回答by Stephen P

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

ES6是现在广泛使用(2019年10月3日),因此设备的完整性-你可以使用箭头操作符.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 ]

回答by Hanlet Esca?o

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

你可以使用forEach,如果你想保留的话,你可以这样做的长度:

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:

或者,您可以有一个小的 POJO 对象,以便于访问:

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 mapto get the same POJO:

或者使用map来获取相同的 POJO:

var words = chars.map(function(str) { 
    return {word: str, length: str.length};
});