📜  Underscore.js _.ternary() 方法

📅  最后修改于: 2022-05-13 01:56:43.556000             🧑  作者: Mango

Underscore.js _.ternary() 方法

Underscore.js _.ternary()方法返回一个只接受三个参数的新函数并将这些参数传递给给定的函数。给出的任何附加参数都将被丢弃。

句法:

_.ternary( fun )

参数:此方法接受如上所述和如下所述的单个参数:

  • fun:这是应该用于参数的函数。

返回值:此方法返回一个新函数。

注意:此方法在普通 JavaScript 中不起作用,因为它需要安装underscore-contrib库。可以使用npm install underscore-contrib 安装

示例 1:

Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function fun() {
    return arguments;
}
  
// Making ternary function
var gfgFunc = _.ternary(fun);
  
console.log("Arguments are :",
    gfgFunc(1, 2, 3));


Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function fun() {
    return arguments;
}
  
// Making the ternary function
var gfgFunc = _.ternary(fun);
  
// Arguments more than 3 are excluded
console.log("Arguments are :",
    gfgFunc(1, 2, 3, 4, 5, 6, 7, 8));


Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function add() {
    s=0;
    for (i=0; i<3; i++) {
        s+=arguments[i];
    }
    return s;
}
  
// Making the ternary function
var gfgFunc = _.ternary(add);
  
// Arguments more than 3 are excluded
console.log("Sum of first 3 arguments is :",
    gfgFunc(1, 2, 3, 4, 5, 6, 7));


输出:

Arguments are : [Arguments] { '0': 1, '1': 2, '2': 3 }

示例 2:

Javascript

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function fun() {
    return arguments;
}
  
// Making the ternary function
var gfgFunc = _.ternary(fun);
  
// Arguments more than 3 are excluded
console.log("Arguments are :",
    gfgFunc(1, 2, 3, 4, 5, 6, 7, 8));

输出:

Arguments are : [Arguments] { '0': 1, '1': 2, '2': 3 }

示例 3:在此示例中,我们将添加参数,但只有前 3 个参数将使用此方法。

Javascript

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function add() {
    s=0;
    for (i=0; i<3; i++) {
        s+=arguments[i];
    }
    return s;
}
  
// Making the ternary function
var gfgFunc = _.ternary(add);
  
// Arguments more than 3 are excluded
console.log("Sum of first 3 arguments is :",
    gfgFunc(1, 2, 3, 4, 5, 6, 7));

输出:

Sum of first 3 arguments is : 6