各种语言中的可变参数(java、python、c++、javascript)

索引:

  • java
  • python
  • c++
  • js

1、Java

public class Animal {
    // 接受可变参数的方法
    void eat(String... Objects) {
        for (String x : Objects) {
            System.out.println("我吃了一个" + x + "!");
        }
    }
    // 调用示例
    public static void main(String[] args) {
        Animal dada = new Animal();
        dada.eat("苹果", "南瓜饼", "土豆");
    }
    /* outputs:
        我吃了一个苹果!
        我吃了一个南瓜饼!
        我吃了一个土豆!
     */
}

 

2、Python

>>> def f(*args, **kw):
...     print(args)
...     print(kw)
...
>>> f(1, 2, 3, name = 'dada', age = 5)
(1, 2, 3)
{'age': 5, 'name': 'dada'}

可以理解为将位置参数收集为一个叫做args的tuple,将关键字参数收集为一个叫做kw的dict。

PS. 位置参数、关键字参数应该是Python特有的…

 

3、C++

#include <iostream>
#include <initializer_list>
using namespace std;
int sum(initializer_list<int> il)
{
    int sum = 0;
    for (auto &x : il) {
        sum += x;
    }
    return sum;
}
int main()
{
    cout << sum({1, 2, 3, 4, 5}) << endl; // output=15
    return 0;
}

 

4、js

const ilike = (...foods) => {
    for (let x of foods) {
        console.log(`i like eat ${x}`);
    }
};
ilike('apple', 'chicken');
=> i like eat apple
=> i like eat chicken

PS. 请忽略语法错误…

三点号还能这么用:

let words = ["never", "fully"];
console.log(["will", ...words, "understand"]);
// → ["will", "never", "fully", "understand"]

 

原文链接:https://www.cnblogs.com/xkxf/p/6617258.html
本文来源 爱码网,其版权均为 原网址 所有 与本站无关,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源。

© 版权声明

相关文章