當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。