yihong0618 / gitblog

People Die, but Long Live GitHub

Home Page:https://yihong0618.github.io/gitblog/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

前端存档

yihong0618 opened this issue · comments

  1. 判断数组是否为空
if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

在 js中 [1] in [[1,2], [1], [1,2,3]] 无论是includes 还是indexof都不好用。

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

//从第 2 位开始删除 0 个元素,插入“drum”
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");
//从第 2 位开始删除 0 个元素,插入“drum” 和 "guitar"
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(2, 0, 'drum', 'guitar');
// 从第 3 位开始删除 1 个元素
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
var removed = myFish.splice(2, 1, "trumpet")

js 判断是否为回文数

function palindrome(str) {
 // Step 1. The first part is the same as earlier
 var re = /[^A-Za-z0-9]/g; // or var re = /[\W_]/g;
 str = str.toLowerCase().replace(re, '');

 // Step 2. Create the FOR loop
 var len = str.length; // var len = "A man, a plan, a canal. Panama".length = 30
 
 for (var i = 0; i < len/2; i++) {
   if (str[i] !== str[len - 1 - i]) { // As long as the characters from each part match, the FOR loop will go on
       return false; // When the characters don't match anymore, false is returned and we exit the FOR loop
   }

slice() works like substring() with a few different behaviors.

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:

If start equals stop: returns an empty string
If stop is omitted: extracts characters to the end of the string
If either argument is greater than the string's length, the string's length will be used instead.
Distinctions of substring():

If start > stop, then substring will swap those 2 arguments.
If either argument is negative or is NaN, it is treated as if it were 0.
Distinctions of slice():

If start > stop, slice() will return the empty string. ("")
If start is negative: sets char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
If stop is negative: sets stop to: string.length – Math.abs(stop) (original value), except bounded at 0 (thus, Math.max(0, string.length + stop)) as covered in the ECMA specification.
Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()

let arr = new Array(m).fill(Array(n).fill(1).....

这个东西是浅拷贝,必须用深拷贝,妈的
let m = Array.from({length: 6}, e => Array(12).fill(0));

嵌套数组如何set 和判断是否在数组中

  1. 先排序
  2. Array.from(new Set(result.map(JSON.stringify)), JSON.parse)