簡體   English   中英

Javascript 鏈接

[英]Javascript chaining

這可能是非常基本的,但我無法理解鏈接和返回是如何同時工作的,例如

let array = [1, 2, 3]
let newArray = array.map(val => val * 10).map(val => val * 10)
console.log(newArray) // [100, 200, 300]

這里我們可以繼續添加.map,它會不斷返回一個新的數組。 它的行為就像鏈接停止時它現在知道它必須返回值但當鏈接繼續時它一直將其視為 object。這是如何工作的以及我如何在我的代碼中實現類似的功能。

它是如何工作的以及我如何在我的代碼中實現類似的功能。

我不確定你是什么意思。 JS 中的數組對象具有map()方法,該方法始終返回由您傳遞的回調 function 修改的新數組val => val * 10

您可以將此表達式視為[1,2,3].map(val => val * 10) // same as [10,20,30] ,並且在數組上鏈接 map 方法將起作用,因為您將始終獲得一個數組,你可以再次使用數組原型方法(它從左到右同步工作)

如果您嘗試不返回數組的鏈接方法,例如[1,2,3].forEach(val => val * 10).map(i => i) ,當 map 將被執行(forEach 不返回任何值,因此在 undefined 上調用 map 方法將拋出 TypeError)。 這就是鏈接的工作原理,您需要始終使用正確的類型,並確保每個方法都是在正確的類型上調用的(映射在數組上,toUpperCase 在字符串上等)。

Array.prototype.map是一種在數組上調用的方法,將給定的 function 應用於每個元素並返回修改后的數組 這樣,您就可以在其上調用其他方法。 類似的方法是Array.prototype.filterArray.prototype.reduce 它們以類似的方式工作,因為您也可以將它們鏈接起來。

為了理解基本的變化,讓我們做一個 function 來刪除字符串的第一個字母,有點像Array.prototype.shift()

// create the strShift function
// it has to be a normal function to access this
const strShift = function(amount = 1){

    // return the output of the function, so that you can 
    // chain another prototypical function
    return this.slice(amount);
}

// add the function to the prototype of String so that its available
// with the dot syntax on all Strings for every future String you 
// create after this point in the code
String.prototype.strShift = strShift;

const myStr = "Hello";
// prints "ello"
console.log(myStr.strShift()) 

JSFiddle 鏈接

有了這個,我們可以看看how chaining and return works at the same time 為此,讓我們制作一個 function 來反轉字符串中每個字符的大小寫。

const strFlipCase = function(){
    // create a temporary variable to then return after the loop.
    const result = [];

    // get an array with each letter
    const strArr = this.split('');

    // loop over the newly created array
    for(let character of strArr){
      // check whether the character is uppercase
      if(character.toUpperCase() === character){
        // character is uppercase so push the lowercase character
        // into the temporary array
        result.push(character.toLowerCase())
      } else {
        // character is lowercase so push the uppercase character
        // into the temporary array
        result.push(character.toUpperCase())
      }
  }
  // temporary array has been filled, return the temporary variable
  // as a string
  return result.join('')
}
String.prototype.strFlipCase = strFlipCase;

const myStr = "Hello";
// prints "hELLO"
console.log(myStr.strFlipCase());

JSFiddle 鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM