Javascript 链接

Javascript chaining

提问人:wallgeek 提问时间:7/17/2020 更新时间:7/17/2020 访问量:169

问:

这可能是非常基本的,但我无法理解链接和返回如何同时工作,例如

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

在这里,我们可以继续添加 .map,它将继续返回一个新数组。它的行为就像当链接停止时一样,它现在知道它必须返回值,但是当链接继续时,它会一直将其视为对象。这是如何工作的,我如何在我的代码中实现类似的功能。

JavaScript的 方法链

评论

0赞 Nikita Madeev 7/17/2020
Array.map 返回 new 数组,它也有一个方法。实际问题或预期结果是什么?.map
0赞 Liam 7/17/2020
真的不清楚你的实际问题是什么?

答:

-1赞 garritfra 7/17/2020 #1

Array.prototype.map 是在数组上调用的方法,将给定的函数应用于每个元素并返回修改后的数组。这样,您可以对其调用其他方法。类似的方法是 Array.prototype.filterArray.prototype.reduce。它们以类似的方式工作,因为您也可以链接它们。

-1赞 Twiggeh 7/17/2020 #2

为了理解基本的吟唱,让我们创建一个函数来删除字符串的第一个字母,有点像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

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 链接

0赞 Robson 7/17/2020 #3

这是如何工作的,我如何在我的 法典。

我不确定你的意思。JS 中的数组对象具有方法,该方法始终返回由您传递的回调函数修改的新数组。map()val => val * 10

你可以把这个表达式看作是 ,在数组上链接映射方法将起作用,因为你总是会得到一个数组,你可以再次使用数组原型方法(它从左到右同步工作)[1,2,3].map(val => val * 10) // same as [10,20,30]

如果您尝试链接不返回数组的方法,例如 ,您将在执行 map 时收到 TypeError(forEach 不返回任何值,因此在 undefined 上调用 map 方法将抛出 TypeError)。这就是链接的工作方式,您需要始终使用正确的类型,并确保每个方法都以正确的类型调用(Array 上的 map、String 上的 toUpperCase 等)。[1,2,3].forEach(val => val * 10).map(i => i)