简体   繁体   English

如何选择在函数中将变量分配给哪个参数? -Javascript

[英]How to choose what argument a variable is assigned to in a function? -Javascript

Given a normal function as such; 赋予正常功能;

function descriptions(awesome, cool, alright){
   return (awesome || "no one") + " is awesome. " + cool + " is cool. " +
     + alright + " is alright";
}
descriptions("jane", "jack", "jefferson");
//returns "jane is awesome. jack is cool. jefferson is alright."

I would like to use the same function, but would only like to pass it the final two arguments like so: 我想使用相同的函数,但只想将最后两个参数传递给它,如下所示:

descriptions(cool : "john", alright : "jane"); //I would like a statement similar to this that works.
//should return "no one is awesome. jack is cool. jefferson is alright."

How would the above be done? 以上将如何完成?

Something different syntactically but similar semantically might be achieved using object destructuring 使用对象解构可以实现语法上不同但语义上相似的某些功能

function descriptions({ awesome = 'no one', cool, alright }) {
    return awesome + " is awesome. " + cool + " is cool. " +
     + alright + " is alright";
}

Then you just invoke it with an object with corresponding properties: 然后,您只需使用具有相应属性的对象来调用它:

descriptions({ cool: 'a', alright: 'b'});

That is not possible in any variety of ECMAScript (including JavaScript). 在任何各种ECMAScript(包括JavaScript)中都是不可能的。

It is theoretically possible to do things like use conditional, custom logic: 从理论上讲,可以做一些使用条件自定义逻辑的事情:

function(a,b,c){
   if(arguments.length === 1) {
      // we're in object mode;
      b = a.b
      c = a.c
      a = a.a || 'default';
   }
}

But that is not a built in part of the language. 但这不是语言的一部分。

This is NOT possible, for example: 这是不可能的,例如:

function foo(a,b,c){return a/(b || 1) + c;}
foo({c:1,b:2,a:3})

There is also the possibility to conditionally define values based on number of arguments: 也可以根据参数数量有条件地定义值:

function say (a,b,c) {
   if(arguments.length === 2) {
      c = b;
      b = a;
      a = 'cat';
   }
   console.log('a ' + a + ' likes a ' + b + ' and a ' + c)
}
say('dog', 'bone', 'walk') // a dog likes a bone and a walk
say('mouse', 'bowl of milk') // a cat likes a mouse and a bowl of milk

Yes you can certainly achieve this! 是的,您当然可以实现! You can use a clever trick many developers use to set a variable to a default value if one is not provided. 如果没有提供变量,您可以使用许多开发人员使用的巧妙技巧将变量设置为默认值。

function descriptions(awesome, cool, alright){
awesome = awesome || "";
if (awesome === "")
{
    return "no one" + " is awesome. " + cool + " is cool. " +
 + alright + " is alright";
}
else{
    return awesome + " is awesome. " + cool + " is cool. " +
 + alright + " is alright";
}

}
console.log(descriptions(undefined, "jack", "jefferson"));

Here is the working code. 这是工作代码。 You could also pass an empty string. 您还可以传递一个空字符串。

In ECMAScript 6, this can sort of be done if you change your parameters to receive an object and take advantage of destructuring assignment . 在ECMAScript 6中,如果您更改参数以接收对象并利用分解分配的优势,则可以完成此操作。

 function descriptions({awesome: awesome = "no one", cool: cool = "", alright: alright = ""} = {}) { return awesome + " is awesome. " + cool + " is cool. " + alright + " is alright"; } var res = descriptions({ cool: "john", alright: "jane" }); document.body.textContent = res; 

So we have someone of an emulation of named parameters. 因此,我们可以模拟命名参数。 Only thing extra needed by the caller is the curly braces. 大括号是呼叫者唯一需要的东西。

Of course browser support is limited, but transpilers are available. 当然,对浏览器的支持是有限的,但是可以使用编译器。

You can do this by passing an object: 您可以通过传递一个对象来做到这一点:

function descriptions(info) {
    // Avoid TypeError if no argument is passed
    if (!info) {
        info = {};
    }

    return (info.awesome || "no one") + " is awesome. " + (info.cool || "no one") + " is cool. " + (info.alright || "no one") + " is alright.";
}

// Use:
console.log(descriptions({
    awesome: "Strong Bad",
    cool: "The Cheat",
    alright: "Strong Sad"
}));

You could use a different approach: 您可以使用其他方法:

var coolLevels = {
  isCool: ["Jack", "John"]
, isAlright: ["Jane", "Jefferson"]
, isAwesome: []
}

function describe(people, coolLevel, phrase) {
  return people.filter(function(person){
    return Boolean(coolLevel.indexOf(person))
  }).join(", ") + phrase
}

function descriptions(people){
  var awesome = describe(people, coolLevels.isAwesome, ' is awesome.')
  var cool = describe(people, coolLevels.isCool, ' is cool.')
  var alright = describe(people, coolLevels.isCool, ' is alright.')

  return awesome + cool + alright
}

demo: https://jsbin.com/kahawuhelu/edit?js,console,output 演示: https : //jsbin.com/kahawuhelu/edit?js,控制台,输出

You can pass undefined , null or "" as the first parameter. 您可以传递undefinednull""作为第一个参数。 Eg: 例如:

descriptions(null, "jack", "jefferson");

Since you already use awesome || "no one" 由于您已经使用了awesome || "no one" awesome || "no one" , any falsy value will be good enough. awesome || "no one" ,任何虚假的价值就足够了。


Another approach would be changing the function to receive an object: 另一种方法是更改​​函数以接收对象:

function descriptions(options) {
  return (options.awesome || "no one") + " is awesome. " + options.cool + " is cool. " + 
    options.alright + " is alright";
}

descriptions({ cool: "jack", alright: "jefferson" });

Now, depending on your browser support, you can use ES6 destructuring parameters: 现在,根据您的浏览器支持,您可以使用ES6解构参数:

const descriptions = ({ awesome = 'no one', cool, alright }) => (
  `${awesome} is awesome. ${cool} is cool. ${alright} is alright`
);

descriptions({ cool: 'jack', alright: 'jefferson' });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM