CodeWars上的JavaScript技巧积累

Posted chucklu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeWars上的JavaScript技巧积累相关的知识,希望对你有一定的参考价值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

var animals = [‘ant‘, ‘bison‘, ‘camel‘, ‘duck‘, ‘elephant‘];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

 

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

The reducer function takes four arguments:

  1. Accumulator (acc)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (src)

Your reducer function‘s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.

 

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

var array1 = [‘one‘, ‘two‘, ‘three‘];
console.log(‘array1: ‘, array1);
// expected output: Array [‘one‘, ‘two‘, ‘three‘]

var reversed = array1.reverse(); 
console.log(‘reversed: ‘, reversed);
// expected output: Array [‘three‘, ‘two‘, ‘one‘]

/* Careful: reverse is destructive. It also changes
the original array */ 
console.log(‘array1: ‘, array1);
// expected output: Array [‘three‘, ‘two‘, ‘one‘]

 

以上是关于CodeWars上的JavaScript技巧积累的主要内容,如果未能解决你的问题,请参考以下文章

javascript Codewars扰码

codewars 上的优秀方法

CSS技巧

记录--九个超级好用的 Javascript 技巧

每日一书|JavaScript 经典「红宝书」,几代前端人的入门选择

你想的到想不到的 javascript 应用小技巧方法