Sé que esta pregunta se ha hecho muchas veces, pero no puedo encontrar la solución a mi problema específico. Supongo que necesito refactorizar mi código por completo, pero me vendría bien alguna orientación.
Estoy practicando OOP en Javascript. Me gustaría unirme a una matriz y agregar una conjunción "y" antes del último elemento. De esa manera [1, 2, 3] ==> "1, 2 y 3".
He incluido mi código con los comentarios a continuación. Como verá, la salida actual que obtengo es "1, 2 y 3". ¿Cómo puedo deshacerme de la coma adicional? ¿Estoy haciendo esto de la manera incorrecta?
class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { // store the index of the last element of the array in a variable called index let index = this.interests.length - 1; // store the conjunction for end of array let conjunction = " and" // insert the conjunction before last element in array this.interests.splice(index, 0, conjunction) // join the array into a string separated by commas let interestsString = this.interests.join(", "); console.log(interestsString); } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());Use Intl.ListFormat() para convertir la lista en una cadena mientras maneja el separador y la conjunción:
const listFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { return listFormatter.format(this.interests); } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());Otra opción es usar la manipulación de matrices: si la matriz contiene solo un elemento, devolver ese elemento. Si contiene más de un elemento, cree una nueva matriz con todos los elementos originales, excepto el último, y el último elemento después de agregarle "y". Únete a la matriz.
class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { return this.interests.length > 1 // if there are multiple items ? [ ...this.interests.slice(0, -1), // get all items but the last `and ${this.interests.at(-1)}` // add the last item with "and" ].join(', ') // join : this.interests.at(0); // just take the single existing item } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());Aquí hay una forma de hacer lo que necesita.
class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { let interestsString = this.interests.join(', ').replace(/, ([^,]*)$/, ' and $1') console.log(interestsString); } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());cuando usaste un empalme como este
this.interests.splice(index, 0, conjunction)agrega el elemento a la matriz, luego la función de combinación agregó otro "," mejor simplemente cambiar el elemento en sí mismo y agregarle y.
como esto:
let changeTo = conjunction + this.interests[index]; this.interests.splice(index, 1, changeTo);