笑咖

文章 评论 浏览 28

笑咖 2025-02-10 05:13:43

这里有多个问题。首先,这不是列表:

randomNames: 'chad', 'bob', 'alice'

那只是一个字符串。如果您想要一个列表,请写:

randomNames: [chad, bob, alice]

或:(

randomNames:
  - chad
  - bob
  - alice

我已经删除了报价,因为它们不是必需的,但是您可以编写'chad',而不是 chad ,等,如果您愿意)。


其次,此任务...

- name: Define random number
  set_fact:
    numberNames:  "{{ range(9,14) }} | random }}"

...没有产生列表;它返回一个数字。因此,在随后的任务中,当您编写时:

- name: Add random names to file
  lineinfile:
    src: {{ randomNames }}
    dest: namesList.txt
  loop: "{{ numberNames }}"

您正在尝试循环浏览 10 之类的内容。


最后, lineInfile 模块没有 src 参数。

如果您的目标是将 n 随机名称写入文件,则可能需要
>过滤器,将一个随机列表随机:

- hosts: localhost
  gather_facts: false
  vars:
    "randomNames": [
      "Bob", "Alice", "James", "Robert", "John", "Michael", "David", "William", "Richard",
      "Joseph", "Thomas", "Charles", "Christopher", "Daniel", "Matthew", "Anthony", "Mark",
      "Donald", "Steven", "Paul", "Andrew", "Joshua", "Mary", "Patricia", "Jennifer",
      "Linda", "Elizabeth", "Barbara", "Susan", "Jessica", "Sarah", "Karen", "Lisa",
      "Nancy", "Betty", "Margaret", "Sandra", "Ashley", "Kimberly", "Emily", "Donna",
      "Michelle"]

  tasks:
    - name: Define random number
      set_fact:
        numberNames: "{{ range(9,14) | random }}"

    - name: Add a random name to a file
      lineinfile:
        path: namesList.txt
        line: "{{ item }}"
      loop: "{{ (randomNames|shuffle)[:numberNames|int] }}"

There are multiple problems here. First, this isn't a list:

randomNames: 'chad', 'bob', 'alice'

That's just a string. If you want a list, write:

randomNames: [chad, bob, alice]

Or:

randomNames:
  - chad
  - bob
  - alice

(I've dropped the quotes, because they're not necessary, but you can write 'chad' instead of chad, etc, if you prefer).


Second, this task...

- name: Define random number
  set_fact:
    numberNames:  "{{ range(9,14) }} | random }}"

...does not produce a list; it returns a single number. So in the subsequent task, when you write:

- name: Add random names to file
  lineinfile:
    src: {{ randomNames }}
    dest: namesList.txt
  loop: "{{ numberNames }}"

You're trying to loop over something like the value 10.


Lastly, the lineinfile module doesn't have a src parameter.

If your goal is to write N random names to a file, you might want
the shuffle filter, which randomizes a list:

- hosts: localhost
  gather_facts: false
  vars:
    "randomNames": [
      "Bob", "Alice", "James", "Robert", "John", "Michael", "David", "William", "Richard",
      "Joseph", "Thomas", "Charles", "Christopher", "Daniel", "Matthew", "Anthony", "Mark",
      "Donald", "Steven", "Paul", "Andrew", "Joshua", "Mary", "Patricia", "Jennifer",
      "Linda", "Elizabeth", "Barbara", "Susan", "Jessica", "Sarah", "Karen", "Lisa",
      "Nancy", "Betty", "Margaret", "Sandra", "Ashley", "Kimberly", "Emily", "Donna",
      "Michelle"]

  tasks:
    - name: Define random number
      set_fact:
        numberNames: "{{ range(9,14) | random }}"

    - name: Add a random name to a file
      lineinfile:
        path: namesList.txt
        line: "{{ item }}"
      loop: "{{ (randomNames|shuffle)[:numberNames|int] }}"

Ansible-从列表中选择多个随机名称

笑咖 2025-02-10 03:27:03

您可以使用类似的放置变量:

 woocommerce_form_field( 'cstm_leeftijd'.$i, array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-first'),
            'label'         => __('Leeftijd bij start Summer Camp'),
            'required' => true,
            'placeholder'   => __( 'Selecteer', 'njengah' ),
            'options'       => array(
                 '4'         => __( '4', 'njengah' ),
                 '5'         => __( '5', 'njengah' ),
                 '6'         => __( '6', 'njengah' ),
                 '7'         => __( '7', 'njengah' ),
                 '8'         => __( '8', 'njengah' ),
                 '9'         => __( '9', 'njengah' ),
                 '10'        => __( '10', 'njengah' ),
                 '11'        => __( '11', 'njengah' )
        )), $checkout->get_value( 'cstm_leeftijd'.$i ));

you can use a placholder variable like this:

 woocommerce_form_field( 'cstm_leeftijd'.$i, array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-first'),
            'label'         => __('Leeftijd bij start Summer Camp'),
            'required' => true,
            'placeholder'   => __( 'Selecteer', 'njengah' ),
            'options'       => array(
                 '4'         => __( '4', 'njengah' ),
                 '5'         => __( '5', 'njengah' ),
                 '6'         => __( '6', 'njengah' ),
                 '7'         => __( '7', 'njengah' ),
                 '8'         => __( '8', 'njengah' ),
                 '9'         => __( '9', 'njengah' ),
                 '10'        => __( '10', 'njengah' ),
                 '11'        => __( '11', 'njengah' )
        )), $checkout->get_value( 'cstm_leeftijd'.$i ));

如何在WooCommerce中选择第一个选项选择“无法选择”字段?

笑咖 2025-02-10 02:33:24
  • 转到Python文件夹 python36/lib/site-packages/scipy/
  • open __ init __. py

更改:

from scipy._lib._testutils import PytestTester

to:to:

from scipy._lib.test__testutils import PytestTester

它在我的Windows 7上工作

  • Go to python folder python36/Lib/site-packages/scipy/
  • Open __init__.py

Change:

from scipy._lib._testutils import PytestTester

to:

from scipy._lib.test__testutils import PytestTester

It worked on my windows 7

Python:源代码字符串不能包含null字节

笑咖 2025-02-10 01:47:38

就我而言,删除 Yarn.lock 文件解决了问题。

In my case, deleting the yarn.lock file solved the problem.

npm err!代码err_socket_timeout npm err!网络套接字超时

笑咖 2025-02-10 00:56:44

This is probably due to incompatible version of the elasticsearch dependency. From https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#getting-started-compatibility it seems you need 7.10 or 7.16 but you have 7.6 dependency. Also check server version to be sure.

方法不存在:org.elasticsearch.client.requestoptions $ builder.setRequestConfig(lorg/apache/http/client/client/config/requestconfig;)

笑咖 2025-02-09 21:30:08

首先,您无需设置 primary_key 字段,因为Django会为您做到这一点。因此,您最好分别从3个模型中删除 project_id site_id sigsion> sistienment_id 字段。
并且在 createNewprojetserial 中存在一些错误。
site_name 分配了_to_id 字段应为 read_only ,如果您无法使用相关对象上传,则需要其他字段才能接收有效载荷。

class CreateNewProjetSerial(serializers.ModelSerializer):
    site_name = ProjectSiteSerializer(many=True, read_only = True)
    assigned_to_id = AssignedUserSerializer(many=True, read_only = True)
    site_names = serializers.ListField(
        child = serializers.CharField(), write_only = True)
    user_ids = serializers.ListField(
        child = serializers.IntegerField(), write_only = True)

    class Meta:
        model = Project
        fields = ['site_name','project_name','assigned_to_id', 'site_names', 'user_ids']
   
    def create(self, validated_data):
        site_names = validated_data.pop('site_names')
        user_ids = validated_data.pop('user_ids')
        
        new_project = Project.objects.create(**validated_data)
  
        for site_name in site_names:
            new_project_site = ProjectSite.objects.create(project_id=new_project, site_name=site_name)            
            
            for user_id in user_ids:    
                Assignment.objects.create(assigned_to_id__id=user_id, site_id=new_project_site)
  
        return new_project

在前端,请像以下内容上传。

{
    "site_names": ["site1", "site2"],
    "project_name": "test_project",
    "user_ids": [2, 3]
}

First, you don't need to set the primary_key fields because django will do that for you. So you'd better remove project_id, site_id, assignment_id field from the 3 models respectively.
And some errors exist in the CreateNewProjetSerial.
site_name, assigned_to_id field should be read_only, and the additional fields are required to receive your payload if you can't upload them with the related object.

class CreateNewProjetSerial(serializers.ModelSerializer):
    site_name = ProjectSiteSerializer(many=True, read_only = True)
    assigned_to_id = AssignedUserSerializer(many=True, read_only = True)
    site_names = serializers.ListField(
        child = serializers.CharField(), write_only = True)
    user_ids = serializers.ListField(
        child = serializers.IntegerField(), write_only = True)

    class Meta:
        model = Project
        fields = ['site_name','project_name','assigned_to_id', 'site_names', 'user_ids']
   
    def create(self, validated_data):
        site_names = validated_data.pop('site_names')
        user_ids = validated_data.pop('user_ids')
        
        new_project = Project.objects.create(**validated_data)
  
        for site_name in site_names:
            new_project_site = ProjectSite.objects.create(project_id=new_project, site_name=site_name)            
            
            for user_id in user_ids:    
                Assignment.objects.create(assigned_to_id__id=user_id, site_id=new_project_site)
  
        return new_project

And in frontend, please upload like the following.

{
    "site_names": ["site1", "site2"],
    "project_name": "test_project",
    "user_ids": [2, 3]
}

如何使用django Rest框架在嵌套仪式对象中创建三个表

笑咖 2025-02-09 19:41:24

我能想到的最简单的解决方案是将您执行的每个操作保存到任务对象中,并将每个对象添加到列表中。迭代完成后,请将列表传递给 tasks#wherallsuccess(collection> task; task; task; task; tasks)您可以看到的方法在以下代码中:

List<Task<DocumentSnapshot>> tasks = new ArrayList<>();
for (String id : ids) {
    Task<DocumentSnapshot> task = db.collection("Collection").document(id).get();
    tasks.add(task);
}
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
        //Do what you need to do with your list
        for (Object object : list) {
            ModelClass mc = ((DocumentSnapshot) object).toObject(ModelClass.class);
        }
    }
});

The simplest solution I can think of would be to save each operation you perform into a Task object and add each object to a List. As soon as the iteration completes, pass that list to Tasks#whenAllSuccess(Collection> tasks) method, as you can see in the following lines of code:

List<Task<DocumentSnapshot>> tasks = new ArrayList<>();
for (String id : ids) {
    Task<DocumentSnapshot> task = db.collection("Collection").document(id).get();
    tasks.add(task);
}
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
        //Do what you need to do with your list
        for (Object object : list) {
            ModelClass mc = ((DocumentSnapshot) object).toObject(ModelClass.class);
        }
    }
});

如何在Firestore中将文件分组在一起?

笑咖 2025-02-09 18:50:16

每个其他答案都解释了为什么这实际上是一种不错的所需行为,或者为什么您无论如何都不需要这个。我的是为那些想要行使自己的权利将语言屈服于自己的意志而不是相反的顽固的人。

我们将使用装饰器“修复”此行为,该行为将复制默认值,而不是重复使用其默认值的每个位置参数相同的实例。

import inspect
from copy import deepcopy  # copy would fail on deep arguments like nested dicts

def sanify(function):
    def wrapper(*a, **kw):
        # store the default values
        defaults = inspect.getargspec(function).defaults # for python2
        # construct a new argument list
        new_args = []
        for i, arg in enumerate(defaults):
            # allow passing positional arguments
            if i in range(len(a)):
                new_args.append(a[i])
            else:
                # copy the value
                new_args.append(deepcopy(arg))
        return function(*new_args, **kw)
    return wrapper

现在,让我们使用此装饰器重新定义我们的功能:

@sanify
def foo(a=[]):
    a.append(5)
    return a

foo() # '[5]'
foo() # '[5]' -- as desired

对于采用多个参数的功能,这尤其整洁。比较:

# the 'correct' approach
def bar(a=None, b=None, c=None):
    if a is None:
        a = []
    if b is None:
        b = []
    if c is None:
        c = []
    # finally do the actual work

重要的是

# the nasty decorator hack
@sanify
def bar(a=[], b=[], c=[]):
    # wow, works right out of the box!

要注意,如果您尝试使用关键字args,则上述解决方案会破裂,例如:

foo(a=[4])

可以调整装饰器以允许这样做,但是我们将其作为读者的练习;)

Every other answer explains why this is actually a nice and desired behavior, or why you shouldn't be needing this anyway. Mine is for those stubborn ones who want to exercise their right to bend the language to their will, not the other way around.

We will "fix" this behavior with a decorator that will copy the default value instead of reusing the same instance for each positional argument left at its default value.

import inspect
from copy import deepcopy  # copy would fail on deep arguments like nested dicts

def sanify(function):
    def wrapper(*a, **kw):
        # store the default values
        defaults = inspect.getargspec(function).defaults # for python2
        # construct a new argument list
        new_args = []
        for i, arg in enumerate(defaults):
            # allow passing positional arguments
            if i in range(len(a)):
                new_args.append(a[i])
            else:
                # copy the value
                new_args.append(deepcopy(arg))
        return function(*new_args, **kw)
    return wrapper

Now let's redefine our function using this decorator:

@sanify
def foo(a=[]):
    a.append(5)
    return a

foo() # '[5]'
foo() # '[5]' -- as desired

This is particularly neat for functions that take multiple arguments. Compare:

# the 'correct' approach
def bar(a=None, b=None, c=None):
    if a is None:
        a = []
    if b is None:
        b = []
    if c is None:
        c = []
    # finally do the actual work

with

# the nasty decorator hack
@sanify
def bar(a=[], b=[], c=[]):
    # wow, works right out of the box!

It's important to note that the above solution breaks if you try to use keyword args, like so:

foo(a=[4])

The decorator could be adjusted to allow for that, but we leave this as an exercise for the reader ;)

&quot“至少惊讶”和可变的默认论点

笑咖 2025-02-09 17:22:52

对索引器进行范围和多线程,以在并行模式下支持重新索引。它通过索引器的维度并行,并跨多个线程执行,从而减少了处理时间。

检查一下
https://devdocs.magento.com/guides/guides/config-guide/config-guide/cli/cli/config-cli-cli-cli-cli-subcommands-index-commands-index。 html#:〜:text = index%20Parallelization%20相:20scoped%20 indexers,be%20Paraled%20By%20 store%20Views

也许可以帮助:)

Indexers are scoped and multi-threaded to support reindexing in parallel mode. It parallelizes by the indexer’s dimension and executes across multiple threads, reducing processing time.

check this
https://devdocs.magento.com/guides/v2.4/config-guide/cli/config-cli-subcommands-index.html#:~:text=Index%20parallelization%20affects%20scoped%20indexers,be%20paralleled%20by%20store%20views.

maybe it can help :)

Reindex Magento 2与Morethan 500000产品

笑咖 2025-02-09 13:12:26

当您创建 pendingIntent 时,

PendingIntent pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, MID,intent1, 0);

请检查您不会传递相同的请求代码 MID 。在这种情况下,Android“重用”以前创建的未决意图,这就是为什么您只会看到最新的通知而不是几个通知。

避免问题的最简单方法似乎是传递不同的请求代码(或其他参数,例如不同的 setAction(...) - 参见下面的链接)。

有关更多信息,请浏览一下Android如何比较即将出现的意图: >

When you are creating a PendingIntent here

PendingIntent pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, MID,intent1, 0);

please check that you aren't passing the same request code MID. In this case Android "reuses" the pending intent which were created previously, that's why you would see only the latest notification instead of several notifications.

It seems the easiest way to avoid the issue would be passing different request codes (or another params, for example different setAction(...) - see the link below) for every type of notifications.

For more info please have a look at how Android compares pending intents: https://stackoverflow.com/a/20205696/2219237

在Android Studio中显示多次每日重复通知

笑咖 2025-02-08 13:03:36

此方法可在某些版本的猫鼬上使用,因此您可以尝试以下方法:

 await Booking.findById({ _id })
  .populate({ 
   path: 'routeId',
      populate: {
         path: 'Bus',
         model: Bus,
         select:"-_id busNumber"
   } 
 })

This method works on some versions of mongoose, So you can try this:

 await Booking.findById({ _id })
  .populate({ 
   path: 'routeId',
      populate: {
         path: 'Bus',
         model: Bus,
         select:"-_id busNumber"
   } 
 })

如何在猫鼬中填充嵌套对象?

笑咖 2025-02-08 01:39:17

您可以简单地列出所需字段,然后仅在最终结果行中将它们推出以显示,例如,

const auditReportConsol = () => {
  const folder = DriveApp.getFolderById('1Y2QgLbHncLzPDe-UCD6WizSNnHkjkt4z');

  const forms = folder.getFilesByType(MimeType.GOOGLE_FORMS);

  const FIELD_LIST = [7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69];

  const rows = [];

  while (forms.hasNext()) {
      const file = forms.next();
      const form = FormApp.openById(file.getId());
      var formResponses = form.getResponses();
      for (var i = 0; i < formResponses.length; i++) {
        var formResponse = formResponses[i];
        var itemResponses = formResponse.getItemResponses();

        var row = [];
        // Pick required items
        itemResponses.map( (index, item) => FIELD_LIST.indexOf(index) >=0 && row.push(item.getResponse()))

      }     
   }
   // Save rows array into sheet
   var ss = SpreadsheetApp.openById('1Qlv4v5dU6caBnRfa4Z58OBnoT0g3uFEmKewTENsBOLo');
   var sheet = ss.getActiveSheet();
   sheet.clear();
   sheet.getRange(1,1, rows.lengths, rows[0].length)

}

我也可能建议将表单/名称作为第一列以区分不同的表单:

row.unshift(form.getTitle())

You can simply list required fields, and later push only them in final result row to display, like this

const auditReportConsol = () => {
  const folder = DriveApp.getFolderById('1Y2QgLbHncLzPDe-UCD6WizSNnHkjkt4z');

  const forms = folder.getFilesByType(MimeType.GOOGLE_FORMS);

  const FIELD_LIST = [7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69];

  const rows = [];

  while (forms.hasNext()) {
      const file = forms.next();
      const form = FormApp.openById(file.getId());
      var formResponses = form.getResponses();
      for (var i = 0; i < formResponses.length; i++) {
        var formResponse = formResponses[i];
        var itemResponses = formResponse.getItemResponses();

        var row = [];
        // Pick required items
        itemResponses.map( (index, item) => FIELD_LIST.indexOf(index) >=0 && row.push(item.getResponse()))

      }     
   }
   // Save rows array into sheet
   var ss = SpreadsheetApp.openById('1Qlv4v5dU6caBnRfa4Z58OBnoT0g3uFEmKewTENsBOLo');
   var sheet = ss.getActiveSheet();
   sheet.clear();
   sheet.getRange(1,1, rows.lengths, rows[0].length)

}

I might also recommend prepending form Id/Name as first column to distinguish different forms:

row.unshift(form.getTitle())

试图将表格合并到表格中

笑咖 2025-02-07 23:19:18

方法 timetuple()是一个实例方法,您无法在 datetime 类上调用,喜欢

now = datetime.now()
tt = now.timetuple()
timestamp = round(time.mktime(tt))

获取时间戳,只需使用 dateTime.timestamp()

now = datetime.now()
print(round(now.timestamp()))

The method timetuple() is an instance method, you can't call is on datetime class, do like

now = datetime.now()
tt = now.timetuple()
timestamp = round(time.mktime(tt))

For getting the timestamp just use datetime.timestamp()

now = datetime.now()
print(round(now.timestamp()))

time_tuple = dateTime.timetuple()typeError:unbound方法dateTime.timetuple()需要一个参数,这是我遇到的错误。如何解决?

笑咖 2025-02-07 09:46:18

该警告是从该 summarise_all(平均值)引起的,不仅可以在 var1 &amp上计算平均值。 var2 ,但在状态&amp; country 。如果要保留状态 country 作为分组列,则应将它们放入 group_by()

library(dplyr)

df %>%
  group_by(county, state, country,
           period = cut(year, seq(2011, 2021, by = 5), right = FALSE)) %>%
  summarise_all(mean) %>%
  ungroup()

# # A tibble: 10 × 7
#    county state country period       year  var1  var2
#    <chr>  <chr> <chr>   <fct>       <dbl> <dbl> <dbl>
#  1 a      A     AA      [2011,2016)  2013  33.1  69.7
#  2 a      A     AA      [2016,2021)  2018  24.7  73.6
#  3 b      B     BB      [2011,2016)  2013  27.6  72.3
#  4 b      B     BB      [2016,2021)  2018  24.7  83.1
#  5 c      C     CC      [2011,2016)  2013  38.7  75.7
#  6 c      C     CC      [2016,2021)  2018  22.8  66.8
#  7 d      D     DD      [2011,2016)  2013  33.8  72.2
#  8 d      D     DD      [2016,2021)  2018  20.0  83.7
#  9 e      E     EE      [2011,2016)  2013  14.9  71.0
# 10 e      E     EE      [2016,2021)  2018  19.6  70.4

如果分组列是简单的 County 期间,其他分类变量在每个组中都是唯一的,您可以通过将第一个值留在执行 first()时将它们保留下来。代码>总结()。

df %>%
  group_by(county,
           period = cut(year, seq(2011, 2021, by = 5), right = FALSE)) %>%
  summarise(across(!where(is.numeric), first),
            across( where(is.numeric), mean)) %>%
  ungroup()

The warnning results from that summarise_all(mean) calculates averages not only on var1 & var2 but on state & country. If you want to keep state and country as grouping columns, you should put them into group_by():

library(dplyr)

df %>%
  group_by(county, state, country,
           period = cut(year, seq(2011, 2021, by = 5), right = FALSE)) %>%
  summarise_all(mean) %>%
  ungroup()

# # A tibble: 10 × 7
#    county state country period       year  var1  var2
#    <chr>  <chr> <chr>   <fct>       <dbl> <dbl> <dbl>
#  1 a      A     AA      [2011,2016)  2013  33.1  69.7
#  2 a      A     AA      [2016,2021)  2018  24.7  73.6
#  3 b      B     BB      [2011,2016)  2013  27.6  72.3
#  4 b      B     BB      [2016,2021)  2018  24.7  83.1
#  5 c      C     CC      [2011,2016)  2013  38.7  75.7
#  6 c      C     CC      [2016,2021)  2018  22.8  66.8
#  7 d      D     DD      [2011,2016)  2013  33.8  72.2
#  8 d      D     DD      [2016,2021)  2018  20.0  83.7
#  9 e      E     EE      [2011,2016)  2013  14.9  71.0
# 10 e      E     EE      [2016,2021)  2018  19.6  70.4

If the grouping columns are simply county and period, and other categorical variables are unique in each group, you could keep them by just leaving the first values with first() while doing summarise().

df %>%
  group_by(county,
           period = cut(year, seq(2011, 2021, by = 5), right = FALSE)) %>%
  summarise(across(!where(is.numeric), first),
            across( where(is.numeric), mean)) %>%
  ungroup()

用保留的因素计算面板数据的5年平均值

笑咖 2025-02-07 09:25:20

您可以使用降低

来知道 0,5 不是有效的数字,因此您必须用 。<<<<。 /代码>为了正确解析

const data= [

    { "id": 1,
    "exercise": "1.1",
    "name": "Session one",
    "hours": "1"
    },
    { "id": 2,
    "exercise": "1.2",
    "name": "Session two",
    "hours": "4"
    },
    { "id": 3,
    "exercise": "1.3",
    "name": "Session three",
    "hours": "0,5"
    }
]


const total = data.reduce((res, {hours}) => res + parseFloat(hours.replace(',', '.')), 0.)

console.log(total)

you can do it with reduce

be aware that 0,5 is not a valid number so you have to replace , with .in order to parse it correctly

const data= [

    { "id": 1,
    "exercise": "1.1",
    "name": "Session one",
    "hours": "1"
    },
    { "id": 2,
    "exercise": "1.2",
    "name": "Session two",
    "hours": "4"
    },
    { "id": 3,
    "exercise": "1.3",
    "name": "Session three",
    "hours": "0,5"
    }
]


const total = data.reduce((res, {hours}) => res + parseFloat(hours.replace(',', '.')), 0.)

console.log(total)

如何计算总小时数?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文