简体   繁体   English

将“ Hello”追加到数组javascript中每个项目的开头

[英]Appending “Hello” to beginning of each item in an array javascript

I have a homework problem asking me to map over the names array, and return a new array with "Hello," appended to the beginning of each name. 我有一个作业问题,要求我映射到名称数组,并返回带有“ Hello”的新数组,该数组附加在每个名称的开头。

The elements are changed when run for the problem. 运行该问题时,元素会更改。

I have to use an arrow function, and also the map method. 我必须使用箭头功能以及map方法。 I'm having trouble finding how to use both the map method, while making sure it adds "Hello," to each element in the array. 我很难找到如何同时使用两种map方法,同时确保将“ Hello”添加到数组中的每个元素。

This is the code and what I have so far. 这是代码,到目前为止我所拥有的。

Any suggestions? 有什么建议么?

var names = "TBD";

var formalGreeting = () => {
  names.map("Hello," + names)
};

So far this just adds the hello to the first element. 到目前为止,这只是向第一个元素添加了问候。

var names = ['John', 'Max', 'Ellie'];
var namesWithGreeting = (arr) => {
    return arr.map(name => "Hello " + name);
}

namesWithGreeting(names);
//Output: ['Hello John', 'Hello Max', 'Hello Ellie']

You pass in an array to your function, and then use the map method to iterate over all the names, returning a new array with all names concatenated with "Hello ". 您将数组传递给函数,然后使用map方法迭代所有名称,并返回一个新数组,该数组的所有名称均以“ Hello”串联。

This will work-- 这将起作用-

var a=["ashay","neeti"];
var e=(w)=>{return w.map(n=>"Hello "+n)};
alert(e(a));

The map() method calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. map()方法按顺序为数组中的每个元素调用提供的回调函数,然后从结果中构造一个新数组

So in the following code snippet, we are mapping the array names where each element in the array is x an for each element we return back the element with the string Hello, appended before it. 因此,在下面的代码片段中,我们映射了数组names ,其中数组中的每个元素都是x ,对于每个元素,我们返回带有字符串Hello,的元素,并在其后附加字符串。

As mentioned above, the map() does not mutate the current array that is being mapped but returns a new array so all we have to do now is assign the new array that you got from mapping names to the variable newNames . 如上所述, map()不会使正在映射的当前数组发生突变,但是会返回一个新数组,因此我们现在要做的就是将从映射names获得的新数组分配给变量newNames

 var names = ["A", "B", "C"]; var formalGreeting = (array) => { var newNames = array.map(x => { return "Hello," + x; }); console.log(newNames); }; formalGreeting(names); 

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

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