简体   繁体   English

如何用for循环使数组中的字符串复数?

[英]How to make strings in an array plural with a for loop?

The goal of the challenge I'm currently working on is to take an array and add an 's' onto the end of each element of it (hopefully pluralizing each word). 我目前正在研究的挑战的目标是获取一个数组,并在其每个元素的末尾添加一个“ s”(希望将每个单词复数)。

Here's what I was able to come up with, but I'm certain that I'm not doing this correctly: 这是我能想到的,但是我确定我没有正确执行此操作:

var pets = ['dog', 'cat', 'rat'];
for (pets[i] = pets[i] + 's';);
console.log(pets);

I realize I'm probably not all that close to the answer, but this lesson is throwing in a few tips without explaining how/why they work. 我意识到我可能离答案还很遥远,但是本课程仅提供一些提示,而没有说明它们的工作方式/原因。 The entire line of pets[i] = pets[i] + 's'; pets[i] = pets[i] + 's';的整个行pets[i] = pets[i] + 's'; was what was suggested by the lesson. 这是本课所建议的。

I'm hoping to still be able to solve the answer on my own, so if someone could include an explanation as to why the for loop is structured the way you happen to structure it, that would be fantastic! 我希望自己仍然能够解决问题,因此,如果有人可以解释为什么for循环是按照您构造它的方式构造的,那就太好了!

Classic use case for Array#map Array#map经典用例

 var pets = ['dog', 'cat', 'rat']; var pluralVersion = pets.map(function(el) { return el + 's'; }); console.log(pluralVersion); 

But, going with your approach, set the new value for each item in array in a for-loop 但是,按照您的方法,在for-loopfor-loop数组中的每个项目设置新值

 var pets = ['dog', 'cat', 'rat']; for (var i = 0, length = pets.length; i < length; i++) { pets[i] = pets[i] + 's'; } console.log(pets); 

Your for syntax is not correct - it should have three parts, like so: 您的for语法不正确-它应包含三个部分,如下所示:

var pets = ['dog', 'cat', 'rat'];
for (var i = 0; i < pets.length; i++) {   //Initialize i as 0. As long as i is less than the length of items in 'pets', continue looping. With each loop, increment i by 1.
   pets[i] = pets[i] + 's';
}
console.log(pets);

In modern Javascript that makes the idea of immutability very popular, you don't actually change values inside your original array but instead map a function to these values and receive a new array. 在使不变性的想法非常流行的现代Javascript中,您实际上并不更改原始数组中的值,而是函数映射到这些值并接收一个新数组。 It's as easy as 就像

const pets = ['dog', 'cat', 'rat'];
const petsPlural = pets.map(pet => `${pet}s`);

It may overwhelm you so let's deconstruct each part. 它可能会让您不知所措,所以让我们分解每个部分。

First, the map . 首先, map This is a property of every array and is a function. 这是每个数组的一个属性,是一个函数。 When you apply it, you supply a single argument which is, again, a function which is applied to every element in original array one by one. 当您应用它时,您将提供一个参数,该参数又是一个函数,该函数一个接一个地应用于原始数组中的每个元素 As a result, the return value of calling someArray.map is a new array. 结果,调用someArray.map的返回值是一个新数组。 The coolest thing is that original array (in your case, pets ) doesn't get changed. 最酷的是原始数组(在您的情况下为pets )不会被更改。 It preserves original values! 它保留了原始值!

Next, the (...) => ... syntax. 接下来, (...) => ...语法。 It is an arrow function which has been introduced in ES6 and is already supported by most modern browser (not Safari). 这是ES6中已引入的箭头功能 ,大多数现代浏览器(而非Safari)已支持该箭头功能 For example, 例如,

(arg1, arg2) => arg1 + arg2

is a short notation for 是的简写

function (arg1, arg2) {
  return arg1 + arg2
}

And finally, that backtick thing. 最后,这回事。 It is called template literal . 它称为模板文字 Everything that is enclosed in ${ and } within this string is evaluated while whatever is outside is just places as is. 字符串中用${}括起来的所有内容都将被评估,而外部的任何内容都将按原样放置。 In fact, when you write, say 实际上,当你写的时候,说

`${abc}def${123}xyz`

it is equivalent to 它等效于

abc + 'def' + 123 + 'xyz'

So, in this case, 所以在这种情况下

`${pet}s`

is equivalent to 相当于

pet + 's'

You can even see how easy it is now to read this part of the code. 您甚至可以看到现在阅读这部分代码是多么容易。

I assume you are new to JavaScript. 我认为您是JavaScript新手。 If that is not the case then please forgive my previous statement. 如果不是这种情况,请原谅我的先前声明。

In JavaScript, when you use a + between two string objects, the result is an appended string. 在JavaScript中,当您在两个字符串对象之间使用+时,结果是附加的字符串。

What it means is, 意思是

let appendedString = "string1" + "string2" ;
console.log(appendedString)
//output = string1string2

Now, for your example, you were supposed to append an 's' at the end of each string to transform that string into its plural form. 现在,以您的示例为例,您应该在每个字符串的末尾附加一个“ s”,以将该字符串转换为复数形式。

Thus the hint was to iterate over each string using a for loop and append an ''s" to each one of them. 因此,提示是使用for循环遍历每个字符串,并在每个字符串后附加一个“ s”。

Now, for iteration, my first approach would be to use the map function . 现在,对于迭代,我的第一种方法是使用map function But, to be precise it really doesn't matter in this particular exmaple. 但是,确切地说,在这个特殊示例中,这并不重要。 Hope, that makes it clear for you. 希望,这对您来说很清楚。

I loved this question. 我喜欢这个问题。 For this job you don't need any for loop in JS. 对于这项工作,您在JS中不需要任何for循环。 The is Array.prototype.map() ; Array.prototype.map() ; Let's also handle the irregularities. 让我们还处理不合规定之处。

 var pets = ['dog', 'cat', 'rat', 'deer', 'goose', 'mouse'], lut = {mouse: "mice", goose: "geese", deer: "deer"}, pluralPets = pets.map(p => lut[p] ? lut[p] : p+"s"); console.log(pluralPets); 

If you are using the for loop approach which I believe you are looking for, a better way to write Rayon's answer would be; 如果您使用的是我认为您正在寻找的for循环方法,那么写Rayon答案的更好方法是:

 var pets = ['cat', 'dog', 'rat']; var length = pets.length; for (i = 0; i < length; i++) { pets[i] = pets[i] + 's'; } console.log(pets); 

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

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