码迷,mamicode.com
首页 > 编程语言 > 详细

CodeWars上的JavaScript技巧积累

时间:2019-01-13 13:42:22      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:mozilla   VID   rem   algorithm   UNC   dia   bsp   cts   ocs   

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技巧积累

标签:mozilla   VID   rem   algorithm   UNC   dia   bsp   cts   ocs   

原文地址:https://www.cnblogs.com/chucklu/p/10262292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!