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"]

对字符串进行操作的时候,slice(-1)是取最后一位字符。

https://www.codewars.com/kata/56f695399400f5d9ef000af5/solutions/javascript

const correctTail = (body, tail) => body.slice(-1) === tail

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.

在使用这个的时候,需要注意的是,必须先自己封装一个reducer函数,然后传递给reduce方法

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']

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.

The original string is left unchanged.

https://stackoverflow.com/questions/1206911/why-do-i-need-to-add-g-when-using-string-replace-in-javascript

答案1

It isn't required, but by default string.replace in JavaScript will only replace the first matching value it finds. Adding the /g will mean that all of the matching values are replaced.

答案2

The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.

A list of useful modifiers:

  1. g - Global replace. Replace all instances of the matched string in the provided text.
  2. i - Case insensitive replace. Replace all instances of the matched string, ignoring differences in case.
  3. m - Multi-line replace. The regular expression should be tested for matches over multiple lines.

You can combine modifiers, such as g and i together, to get a global case insensitive search.

Examples:

//Replace the first lowercase t we find with X
'This is sparta!'.replace(/t/,'X');
//result: 'This is sparXa!' //Replace the first letter t (upper or lower) with X
'This is sparta!'.replace(/t/i, 'X');
//result: 'Xhis is sparta!' //Replace all the Ts in the text (upper or lower) with X
'This is sparta!'.replace(/t/gi, 'X' );
//result: 'Xhis is sparXa!'

For more information see the JavaScript RegExp Object Reference at the w3schools.

three dots

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

https://stackoverflow.com/questions/31048953/what-do-these-three-dots-in-react-do

This is a feature of es6 which is used in React as well. Look at the below example:

function Sum(x,y,z) {
return x + y + z;
}
console.log(Sum(1,2,3)); //6

This way is fine if we have maximum 3 parameters but what if we need to add for example 110 parameters. Should we define them all and add them one by one?! Of course there is an easier way to do which is called SPREAD. Instead of passing all those parameters you write :

function (...numbers){}

We have no idea how many parameters we have but we know there are heaps of those. Based on es6 we can rewrite the above function as below and use the spread and mapping between them to make it as easy as a piece of cake:

let Sum = (...numbers) => {
return numbers.reduce((prev, current) => prev + current );
}
console.log(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9));//45

get ascii code from  character

https://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript

String.prototype.charCodeAt() can convert string characters to ASCII numbers. For example:

"ABC".charCodeAt(0) // returns 65

For opposite use String.fromCharCode(10) that convert numbers to equal ASCII character. This function can accept multiple numbers and join all the characters then return the string. Example:

String.fromCharCode(65,66,67); // returns 'ABC'

function like range in C#

https://www.codewars.com/kata/reversed-sequence/train/javascript

https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp

https://stackoverflow.com/questions/19544452/remove-last-item-from-array

const reverseSeq = n => {
var temp = [...Array(n + 1).keys()].reverse();
temp.pop();
return temp;
};

Javascript arrays: remove all elements contained in another array

 

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
return toRemove.indexOf( el ) < 0;
} );

Small improvement, as browser support for Array.includes() has increased:

myArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
} );

Next adaption using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

对char表示的数字做加减运算的时候

直接在变量前面放1个+号,就可以

https://www.codewars.com/kata/57eaeb9578748ff92a000009/solutions/javascript

Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.

Return your answer as a number.

function sumMix(x){ return x.map(a => +a).reduce((a, b) => a + b); }

https://stackoverflow.com/questions/15129137/what-does-mean-in-javascript

r = +_;
  • + tries to cast whatever _ is to a number.
  • _ is only a variable name (not an operator), it could be afoo etc.

Example:

+"1"

cast "1" to pure number 1.

var _ = "1";
var r = +_;

r is now 1, not "1".

Moreover, according to the MDN page on Arithmetic Operators:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already[...] It can convert string representations of integers and floats, as well as the non-string values truefalse, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

It is also noted that

unary一元 plus is the fastest and preferred way of converting something into a number

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

var sentence = 'The quick brown fox jumps over the lazy dog.';

var word = 'fox';

console.log(`The word "${word}" ${sentence.includes(word)? 'is' : 'is not'} in the sentence`);
// expected output: "The word "fox" is in the sentence"

函数内部检查,被调用的时候,外部是否进行了传参

https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function

You should actually check typeof argument2 === "undefined", in case someone defines "undefined".

https://stackoverflow.com/questions/11461428/check-if-argument-is-passed-to-a-java-script-function

null is a specific value. undefined is what it will be if it is not passed.

让一个单词的首字母大写

https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript

function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

usage of Date

https://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript

https://www.codewars.com/kata/is-the-date-today/train/javascript

function isToday(date) {
var today = new Date();
var date1 = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
var date2 = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()));
return date1.getTime() === date2.getTime();
}

其他人更简单的解法

function isToday(date) {
return new Date().toDateString() === date.toDateString();
}

判断参数是否为数字

https://stackoverflow.com/questions/6449611/check-whether-a-value-is-a-number-in-javascript-or-jquery

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

没有做完的

//https://www.codewars.com/kata/closest-elevator/train/javascript
function elevator(left, right, call) {
console.log(`${left},${right},${call}`);
var middle = (left + right) / 2;
var delta1 = 0;
var delta2 = 0;
if (left <= right) {
delta1 = Math.abs(middle - left);
delta2 = Math.abs(right - middle);
} else {
delta1 = Math.abs(middle - right);
delta2 = Math.abs(left - middle);
}
var result = 'left';
if (left === right) {
result = 'right';
} else {
if (call <= left) {
result = 'left';
} else if (call >= right) {
result = 'right';
} else {
if (delta2 >= delta1) {
result = 'right';
}
}
}
return result;
}

CodeWars上的JavaScript技巧积累的更多相关文章

  1. ( 译、持续更新 ) JavaScript 上分小技巧(四)

    后续如有内容,本篇将会照常更新并排满15个知识点,以下是其他几篇译文的地址: 第一篇地址:( 译.持续更新 ) JavaScript 上分小技巧(一) 第二篇地址:( 译.持续更新 ) JavaScr ...

  2. ( 译、持续更新 ) JavaScript 上分小技巧(三)

    最近家里杂事较多,自学时间实在少的可怜,所以都在空闲时间看看老外写的内容,学习之外顺便翻译分享~等学习的时间充足些再写写自己的一些学习内容和知识点分析(最近有在接触的:复习(C#,SQL).(学习)T ...

  3. ( 译、持续更新 ) JavaScript 上分小技巧(二)

    考虑到文章过长,不便于阅读,这里分出第二篇,如有后续,每15个知识点分为一篇... 第一篇地址:( 译.持续更新 ) JavaScript 上分小技巧(一) 第三篇地址:( 译.持续更新 ) Java ...

  4. ( 译、持续更新 ) JavaScript 上分小技巧(一)

    感谢好友破狼提供的这篇好文章,也感谢写这些知识点的作者们和将他们整理到一起的作者.这是github上的一篇文章,在这里本兽也就只做翻译,由于本兽英语水平和编程能力都不咋地,如有不好的地方也请多理解体谅 ...

  5. Javascript技巧

    Javascript数组转换为CSV格式 首先考虑如下的应用场景,有一个Javscript的字符型(或者数值型)数组,现在需要转换为以逗号分割的CSV格式文件.则我们可以使用如下的小技巧,代码如下: ...

  6. (译文)12个简单(但强大)的JavaScript技巧(二)

    原文链接: 12 Simple (Yet Powerful) JavaScript Tips 其他链接: (译文)12个简单(但强大)的JavaScript技巧(一) 强大的立即调用函数表达式 (什么 ...

  7. 21个值得收藏的Javascript技巧

    1  Javascript数组转换为CSV格式 首先考虑如下的应用场景,有一个Javscript的字符型(或者数值型)数组,现在需要转换为以逗号分割的CSV格式文件.则我们可以使用如下的小技巧,代码如 ...

  8. Webbrowser控件史上最强技巧全集

    原文:Webbrowser控件史上最强技巧全集 Webbrowser控件史上最强技巧全集 VB调用webbrowser技巧集 1.获得浏览器信息: Private Sub Command1_Click ...

  9. javascript知识点积累

    8年javascript知识点积累   08年毕业就开始接触javascript,当时是做asp.net发现很多功能用asp.net控件解决不了,比如checkbox单选,全选问题,自动计算总价问题, ...

随机推荐

  1. Laravel5.1 路由 -路由分组

    路由分组有啥好处? 有时候啊 一大堆路由它们都有共同的地方,比如都使用一个中间件(过两天写)或是前缀都一样,避免代码重复 我们可以将他们分到一组中. 1 路由分组可以共享哪些属性? 中间件 middl ...

  2. SAP FI 中4个特殊期间

    标准SAP ERP里面有个13-16的4个特殊的会计期间,这4个特殊的会计期间如何使用?作用是什么? SAP记帐期间变式,会计年度与特殊期间. 记帐期间变式是较难理解的一个内容.不过要表达的内容很简单 ...

  3. W​i​n​下​h​t​t​p​d​+​p​h​p​+​m​y​s​q​l​环​境​集​成

    apache+php+mysql: php下载:  VC6就是legacy Visual Studio 6 compiler,就是使用这个编译器编译的,  VC9就是the Visual Studio ...

  4. (七)solr7之Terms组件的使用

    (七)solr7之Terms组件的使用 Terms组件提供访问索引项的字段和每个词相匹配的文档数量. 这可以用于建立一个自动建议特性或任何其他的特性,而这个terms不是搜索或文档级别的水平.快速检索 ...

  5. coursera 《现代操作系统》 -- 第十周 文件系统(2)

    身份验证 Authentication 知道用户是谁.通过账号密码.Id 这样的识别出来. 访问控制 Permission 知道用户是谁后. 主动控制 记录用户ID和对应的访问权限 --> 记录 ...

  6. 数据链路层负载均衡 Linux Virtual Server

    w 李智慧

  7. 修改本机域名localhost为任意你想要的名称

    web项目研发中,测试的时候项目路径与发布以后的路径不一致,项目组之间的路径不一致,这样会加大工作量,这个时候我们可以统一一下开发的路径,这样可以省很多事,话不多说,看下面教程: 在系统盘中的如下路径 ...

  8. Hadoop “Name node is in safe mode” 错误解决方法

    Hadoop 解除 "Name node is in safe mode" 运行hadoop程序时,有时候会报以下错误:org.apache.hadoop.dfs.SafeMode ...

  9. 小计---pandas读取带有中文文件名或者包含中文内容的文件

    python2下: # -*- coding: utf-8 -*- import pandas as pd mydata = pd.read_csv(u"例子.csv") #前面加 ...

  10. Python2 socket 多线程并发 TCPServer Demo

    #coding=utf-8 import socket import threading,getopt,sys,string opts, args = getopt.getopt(sys.argv[1 ...