Javascript尝试格式化名称字符串

时间:2019-02-19 17:27:22

标签: javascript arrays object

尝试输出:

list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'

list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'

list([ {name: 'Bart'} ])
// returns 'Bart'

list([])
// returns ''

我的代码:

function list(names){
  let output = "";
  let length = names.length;
  for(i=0; i < length; i++){
    if(length > 2 && i !== length - 1){
     output += names[i]['name'] + ', ' ;
    }
    else if( i == length - 1 && i !== 0) {
      output += ' & ' + names[i]['name'] ;
    } else{
      output += names[i]['name'];
    }
  }
  return output;
}

预期:“巴特,丽莎,玛姬,荷马和玛格”,而得到:“巴特,丽莎,玛姬,荷马和玛格”

有什么想法为什么if语句不能正常工作?我似乎无法使其正常工作。

5 个答案:

答案 0 :(得分:3)

数组索引从0开始,因此length - 1是数组的最后一个元素,而不是倒数第二个。

在您的第一种情况下,尝试用i !== length - 1替换i < length - 2

function list(names){
  let output = "";
  let length = names.length;
  for(i=0; i < length; i++){
    if(length > 2 && i < length - 2){
     output += names[i]['name'] + ', ' ;
    }
    else if( i == length - 1 && i !== 0) {
      output += ' & ' + names[i]['name'] ;
    } else{
      output += names[i]['name'];
    }
  }
  return output;
}

console.log(list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}, {name: 'Homer'}, {name: 'Marge'} ]))
// returns Bart, Lisa, Maggie, Homer & Marge

console.log(list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]))
// returns 'Bart, Lisa & Maggie'

console.log(list([ {name: 'Bart'}, {name: 'Lisa'} ]))
// returns 'Bart & Lisa'

console.log(list([ {name: 'Bart'} ]))
// returns 'Bart'

console.log(list([]))
// returns ''

使用reduceRight和一些ES6功能对其进行清理,我们也可以这样写:

function list(names){
  let length = names.length;
  if (length === 0) {
    return '';
  }

  return names
    .map(n => n.name)
    .reduceRight((acc, cur, i) => `${cur}${i < length - 2 ? ', ' : ' & '}${acc}`);
}

console.log(list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}, {name: 'Homer'}, {name: 'Marge'} ]))
// returns Bart, Lisa, Maggie, Homer & Marge

console.log(list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]))
// returns 'Bart, Lisa & Maggie'

console.log(list([ {name: 'Bart'}, {name: 'Lisa'} ]))
// returns 'Bart & Lisa'

console.log(list([ {name: 'Bart'} ]))
// returns 'Bart'

console.log(list([]))
// returns ''

答案 1 :(得分:3)

这里的想法是

  1. 从输入的对象数组中获取名称数组。
  2. 现在获取数组的长度。
  3. 使用pop获取数组的最后一个元素。
  4. 现在检查长度是否为0,返回empty string,如果1比我们返回的只是名字,如果大于1,比对输入与{{1} }和,&

last

答案 2 :(得分:1)

import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
from pathlib import Path

class Pdf(object):
    def __init__(self, master):
        self.master = master
        pdf = PdfPages(Path.cwd() / 'demo.pdf')

        self.pdf = pdf

    def plot_initial(self):
        fig = plt.figure(figsize=(8,6))
        fig.add_subplot(111)

        mu, sigma = 0, 0.1
        s = np.random.normal(mu, sigma, 1000)
        count, bins, ignored = plt.hist(s, 30, density=True)
        plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
                 np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
                 linewidth=2, color='r')
        plt.title('Overview')
        plt.xlabel('X')
        plt.ylabel('Y')
        self.pdf.savefig(fig)
        # THE CULPRIT
        plt.close(fig)

    def plot_extra(self):
        fig = plt.figure(figsize=(8,6))
        fig.add_subplot(111)

        mu, sigma = 0, 0.1
        s = np.random.normal(mu, sigma, 1000)
        count, bins, ignored = plt.hist(s, 30, density=True)
        plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
                 np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
                 linewidth=2, color='r')
        plt.title('Extra')
        plt.xlabel('X')
        plt.ylabel('Y')
        self.pdf.savefig(fig)
        plt.close(fig)

    def close(self):
        self.pdf.close()

class MVE(object):
    @classmethod
    def run(cls):
        root = tk.Tk()
        MVE(root)
        root.mainloop()

    def __init__(self, master):
        self.root = master
        tk.Frame(master)

        menu = tk.Menu(master)
        master.config(menu=menu)

        test_menu = tk.Menu(menu, tearoff=0)
        menu.add_cascade(label='Bug', menu=test_menu)
        test_menu.add_command(label='PDF', command=
                              self.generate_pdf)

    def generate_pdf(self):
        pdf = Pdf(self)

        pdf.plot_initial()
        for i in range(0,3):
            pdf.plot_extra()
        pdf.close()

if __name__ == "__main__":
    MVE.run()

您要执行的操作是将集合转换为单个值。您将面对许多不同类型的对象的场景。因此,javascript提供了reduce功能,可将您的数组集合转换为单个累加值。您甚至不需要单独的方法“列表”来解决此问题。 reduce方法简洁明了,对新开发者来说很容易解释,是解决此类问题的最佳方法之一。

引用:https://medium.freecodecamp.org/reduce-f47a7da511a9

答案 3 :(得分:0)

如果不是第一个字母,请检查它是否是最后一个字母。如果它是最后一个加号,则不要在其前加上逗号:

function list(names) {
  let output = "";
  const length = names.length;
  for (i = 0; i < length; i++) {
    if (i > 0) {
      output += i < length - 1 ? ', ' : ' & ';
    }

    output += names[i].name;
  }
  return output;
}

console.log(list([{ name: 'Bart' }, { name: 'Lisa' }, { name: 'Maggie' }])); // returns 'Bart, Lisa & Maggie'

console.log(list([{ name: 'Bart' }, { name: 'Lisa' }])); // returns 'Bart & Lisa'

console.log(list([{ name: 'Bart' }])); // returns 'Bart'

console.log(list([])); // returns ''

您也可以按照相同的逻辑使用Array.map()Array.join()

const addSeparator = (isNotLast) => isNotLast ? ', ' : ' & ';

const list = (names) => 
  names.map(({ name }, i) => i > 0 ? 
    `${addSeparator(i < length - 1)}${name}` : name)
  .join('')


console.log(list([{ name: 'Bart' }, { name: 'Lisa' }, { name: 'Maggie' }])); // returns 'Bart, Lisa & Maggie'

console.log(list([{ name: 'Bart' }, { name: 'Lisa' }])); // returns 'Bart & Lisa'

console.log(list([{ name: 'Bart' }])); // returns 'Bart'

console.log(list([])); // returns ''

答案 4 :(得分:0)

另一个答案是正确的,但只是指出,有一些Array原型方法可以为您提供帮助,而无需完全手动处理索引:

for rows in dataframe_to_rows(df, index=False, header=True):
    ws.append(rows)