Как вернуть все элементы массива с пробелом между ними? - PullRequest
0 голосов
/ 27 января 2020

Я создаю функцию конструктора с некоторыми свойствами и методами. Свойства являются массивами. В этих методах я хочу вернуть фразу с элементами массива. По умолчанию элементы массива представлены без пробелов между ними. Затем я создал для метода l oop внутри метода метод возврата каждого элемента с пробелом между собой и запятой. Оказывается, что когда я go выхожу на консоль и вызываю экземпляр, созданный позднее с помощью метода, он показывает только первый элемент массива. Может кто-нибудь объяснить мне, что я сделал не так и что я должен делать? Спасибо Это мой код:

function People(first, last, age, gender, interest, caracteristic ){
            this.name={
                first:first,
                last:last
            };

            this.age = age;
            this.gender = gender;
            this.interest = interest;
            this.caracteristic = caracteristic;

            this.bio = function() {
                return `${this.name.first} ${this.name.last} is ${this.age}.Is ${this.gender} and likes ${this.interest}`
            }

            this.greeting = function(){
                return ` Hi! I'm ${this.name.first}.`
            }

            this.personality = function(){
                *// here I try to find a way to show all the caracteristic with some space between*
                for(var i = 0 ; i <= caracteristic.length ; i++){
                    let caracteristica = caracteristic[i] + ' ,'
                    return caracteristica
                }               
                 return ` ${this.name.first} is ${caracteristica}`
            }

        }

        let people1 = new People('Sandra',
                                 'Stward', 
                                 47, 
                                 'female',
                                ['arts', 'cinema', 'poetry', 'photography', 'arts and crafts', 'painting', 'drawing', 'creative art'],
                                 ['kind', 'clever', 'sweet', 'empathic', 'emotive', 'hight sensitive person']
                                 )

    </script>

Ответы [ 3 ]

3 голосов
/ 27 января 2020

Возврат в for l oop скоро завершит l oop.

Но для создания разделенной пробелами строки лучше сделать с объединением.

    this.personality = function() {
          return this.name.first + ' is ' + this.caracteristic.join(' ');
    }

Тем не менее, вместо функции, вы также можете использовать Class для этого.

Пример фрагмента:

class People {
     constructor (first, last, age, gender, interest, caracteristic) {
        this.name={
            first: first,
            last: last
        };
        this.age = age;
        this.gender = gender;
        this.interest = interest;
        this.caracteristic = caracteristic;
     }
   
     bio = () => `${this.name.first} ${this.name.last} is ${this.age}.Is ${this.gender} and likes ${this.interest}`;
     greeting = () => `Hi! I'm ${this.name.first}.`;       
     personality = () => `${this.name.first} is ${this.caracteristic.join(' ')}`; 

}

let people1 = new People(
  'Sandra', 'Stward', 47, 'female',
  ['arts', 'cinema', 'poetry', 'photography', 'arts and crafts', 'painting', 'drawing', 'creative art'],
  ['kind', 'clever', 'sweet', 'empathic', 'emotive', 'hight9 sensitive person']
 );
 
console.log(people1.name)
console.log(people1.bio())
console.log(people1.greeting())
console.log(people1.personality())

 
1 голос
/ 27 января 2020

Вы можете использовать Array.join(' ') метод. Или, может быть, Array.reduce, используя строку в качестве аккумулятора, и на каждой итерации объединяйте ток с накопленной строкой.

0 голосов
/ 27 января 2020

Рассмотрим использование Соединение с массивом

console.log(['kind', 'clever', 'sweet', 'empathic', 'emotive', 'hight sensitive person'].join(", "))

Возвращает

"добрый, умный, сладкий, empathi c, эмоциональный, чувствительный к высоте человек "

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...