admin管理员组文章数量:1291760
In the following short script (running in my browser):
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.map(function(age) {
return Math.sqrt(age) + "<br/>";
});
document.write(ages3);
In the following short script (running in my browser):
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.map(function(age) {
return Math.sqrt(age) + "<br/>";
});
document.write(ages3);
I would like to print a column of square root values in the most concise manner possible (ideally using the map method above). I attempted to chain a join, e.g., return age.join(' ').Math.sqrt(age) + "<br/>"; but that was unsuccessful (no output was produced).
Thank you.
Share Improve this question edited May 5, 2018 at 0:43 cs95 402k104 gold badges735 silver badges790 bronze badges asked May 5, 2018 at 0:42 CaitlinGCaitlinG 2,0153 gold badges27 silver badges35 bronze badges5 Answers
Reset to default 14My solution using join
and map
.
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
document.write(
ages.map(a => Math.sqrt(a))
.join("<br>")
);
I think this solution is pretty concise and does just what you want.
If you want to produce a (single) HTML string to output, you should use reduce
instead. .map
is for when you want to transform an array into another array.
const ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.reduce(function(accum, age) {
return accum + Math.sqrt(age) + "<br/>";
}, '');
document.write(ages3);
You were on the right track. Just join()
the newly mapped array ages3
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.map(function(age) {
return Math.sqrt(age) + "<br/>";
});
document.write(ages3.join(' '));
Alternatively you can use array.from
const ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
document.write(Array.from(ages, x => Math.sqrt(x)).join('<br\>'));
if you want new line between result then you can pass < br / > in side join function just line this:- return Math.sqrt(age).join('<br>'); if you want space between result then you can pass empty string in join function jus like this:- return Math.sqrt(age).join(' '); or if you want nothing then you can pas nothing inside jpin function just like this:- return Math.sqrt(age).join('');
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.map(function(age) {
return Math.sqrt(age).join('<br\>');
// return Math.sqrt(age).join(' ');
// return Math.sqrt(age).join('');
});
document.write(ages3);
本文标签: mAPand removing commas from an array in JavascriptStack Overflow
版权声明:本文标题:Map, and removing commas from an array in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738523797a2092230.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论