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


underscore.js _.value()用法及代碼示例

Underscore.js是一個JavaScript庫,它使對數組,字符串,對象的操作更加容易和方便。
_.value()函數用於提取包裝對象的值。此函數主要與JavaScript中的鏈函數一起使用。

注意:在瀏覽器中使用下劃線函數之前,非常有必要鏈接下劃線CDN。鏈接underscore.js CDN時“_”作為全局變量附加到瀏覽器。

用法:

_.chain(obj).value()

參數:此函數不接受任何參數。它具有不同的函數。 “.value()”用於提取對象的值,即數組,字符串等。

返回值:它返回對象類型的對象的值。如果對象是數組,則返回數組;如果對象是字符串,則返回字符串,依此類推。

範例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> 
        let arr = ["c", "d", "a", "b"]; 
        console.log(`original array is ${arr}`); 
  
        // Wrapped object is array so  
        // its values is returned 
        let newArr = _.chain(arr).sort().value(); 
  
        // Changes made in original array. 
        console.log(`original array is ${arr}`); 
        console.log(`new array is ${newArr}`); 
    </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> 
        let str = "geeks for geeks" 
        console.log(`original string is ${str}`); 
  
        // Wrapped object is str so its 
        // values is returned 
        let newstr = _.chain(str).toArray() 
                .reverse().join("").value(); 
  
        // Printing the new string 
        console.log(`new string is ${newstr}`); 
    </script> 
</body> 
  
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Underscore.js _.value() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。