简体   繁体   English

Javascript 链接

[英]Javascript chaining

This might be very basic but I am not able to understand how chaining and return works at the same time like for example这可能是非常基本的,但我无法理解链接和返回是如何同时工作的,例如

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

Here we can keep on adding.map and it will keep returning a new array.这里我们可以继续添加.map,它会不断返回一个新的数组。 It behaves like when chaining stops it knows now that it has to return value but when chaining continues it keeps treating it as object. How does that work and how can I achieve similar functionality in my code.它的行为就像链接停止时它现在知道它必须返回值但当链接继续时它一直将其视为 object。这是如何工作的以及我如何在我的代码中实现类似的功能。

How does that work and how can I achieve similar functionality in my code.它是如何工作的以及我如何在我的代码中实现类似的功能。

I'm not sure what you mean.我不确定你是什么意思。 Array objects in JS have map() method which returns always new array modified by callback function that you're passing val => val * 10 . JS 中的数组对象具有map()方法,该方法始终返回由您传递的回调 function 修改的新数组val => val * 10

You can think of this expression as [1,2,3].map(val => val * 10) // same as [10,20,30] , and chaining map method on array will work because you'll get always an Array and you can again use an array prototype method (it works synchronously from left to right)您可以将此表达式视为[1,2,3].map(val => val * 10) // same as [10,20,30] ,并且在数组上链接 map 方法将起作用,因为您将始终获得一个数组,你可以再次使用数组原型方法(它从左到右同步工作)

If you'll try chaining method that doesn't return an array eg [1,2,3].forEach(val => val * 10).map(i => i) , you'll get a TypeError when map will be executed (forEach doesn't return any value, so calling map method on undefined will throw a TypeError).如果您尝试不返回数组的链接方法,例如[1,2,3].forEach(val => val * 10).map(i => i) ,当 map 将被执行(forEach 不返回任何值,因此在 undefined 上调用 map 方法将抛出 TypeError)。 That's how chaining works, you need to use always correct types and be sure that each method is called on correct type (map on Array, toUpperCase on String etc).这就是链接的工作原理,您需要始终使用正确的类型,并确保每个方法都是在正确的类型上调用的(映射在数组上,toUpperCase 在字符串上等)。

Array.prototype.map is a method that is called on an array, applies the given function to each element and returns the modified array . Array.prototype.map是一种在数组上调用的方法,将给定的 function 应用于每个元素并返回修改后的数组 This way, you can call other methods on it.这样,您就可以在其上调用其他方法。 Similar methods are Array.prototype.filter and Array.prototype.reduce .类似的方法是Array.prototype.filterArray.prototype.reduce They work in a similar way, as you can chain them as well.它们以类似的方式工作,因为您也可以将它们链接起来。

To understand basic chaning lets make a function that removes the first letter of a string, kind of like Array.prototype.shift() ;为了理解基本的变化,让我们做一个 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 Link JSFiddle 链接

With that out of the way, we can look at how chaining and return works at the same time .有了这个,我们可以看看how chaining and return works at the same time For that lets make a function that inverts the case of each character in a string.为此,让我们制作一个 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 Link JSFiddle 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM