当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


underscore.js _.identity()用法及代码示例


Underscore.js是一个JavaScript库,它使对数组,字符串,对象的操作更加容易和方便。
_.identity()函数用于返回与参数一样的值的完全相同的副本。该函数看起来没有用,但是在整个Underscore中都用作默认迭代器。

注意:在浏览器中使用下划线函数之前,非常有必要链接undescore CDN。链接underscore.js CDN时“_”作为全局变量附加到浏览器。

用法:

_.identity( object );

参数:该函数接受单个参数对象。

返回值:此函数返回给定参数的值。



范例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script> 
  
        // Creating a string 
        let str = new String("GeeksforGeeks") 
  
        // _.identity function of underscore.js 
        let copystr = _.identity(str) 
        console.log(`original string is ${str}`) 
        console.log(`Identity string is ${copystr}`) 
    </script> 
</body> 
  
</html>

输出:

范例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script> 
  
        // Creating a object 
        let obj = { 
            "a":1, 
            "b":2, 
            "c":3 
        } 
  
        // _.identity function of underscore.js 
        let copyobj = _.identity(obj) 
        console.log(`original object is ${obj}`) 
        console.log(`Identity object is ${copyobj}`) 
  
        // This will return true 
        console.log(obj === copyobj) 
  
        // Both objects are exactly same 
        console.log("from obj:", obj.a,  
            " from copyobj:", copyobj.a); 
  
        // Made Changes in object 
        obj.a = 12 
  
        // Change in one object  
        // reflects in another 
        console.log("change in one object"
            + " reflects in another =>") 
        console.log("from obj:", obj.a,  
            " from copyobj:", copyobj.a); 
    </script> 
</body> 
  
</html>

输出:




相关用法


注:本文由纯净天空筛选整理自tarun007大神的英文原创作品 Underscore.js _.identity() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。