简体   繁体   English

function 与 array.join -javascript 中的帮助

[英]function with array.join -help in javascript

so before anything my experience with JavaScript is not that much, I'm trying to make a function called hashtag_it with an array and i want to add # before every index in this array so when I call the function the output is going to be #programming,#code, i tried to use array.join method but it didn't really work so before anything my experience with JavaScript is not that much, I'm trying to make a function called hashtag_it with an array and i want to add # before every index in this array so when I call the function the output is going to be #编程,#code,我尝试使用 array.join 方法,但它并没有真正起作用

 function hashtag_it(my_array) { my_array = ['programming','code']; console.log(my_array.join('#')) } console.log(hashtag_it());

 const my_array = ['programming','code']; function hashtag_it() { return my_array.map(item => `#${item}`).join(','); } console.log(hashtag_it(my_array));

.join only joins by a separator after each element. .join仅在每个元素后通过分隔符连接。 You want to add # before each element.您想在每个元素之前添加# What I have changed is I have added map which simply appends # before each element and then you can use join(',') which joins each element using a , as a separator我所做的更改是我添加了map ,它只是在每个元素之前附加# ,然后您可以使用join(',') ,它使用,作为分隔符连接每个元素

References:参考:

You have to add # to all the elements in the array and then join it.您必须将#添加到数组中的所有元素,然后加入它。 Simply using join won't add # to the first element.简单地使用 join 不会将#添加到第一个元素。

 function hashtag_it(my_array) { my_array = ['programming', 'code']; new_array = my_array.map(el => "#" + el).join(",") return new_array } console.log(hashtag_it());

 const array = ["programming", "coding", "dogs"]; const tagIt = (arr) => { return arr.map(word => '#'+word).join(","); }; console.log( tagIt(array) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM