Common knowledge reserve in JS foundation

Summary of JavaScript

1 Grammar

1 ECMAScript-ES specification

1.1 Keywords

  • let
  • const
  • was

1.2 Operators

  • computation

    + - * / %  += -= *= /= %= ++ --
    
  • logic operation

    &&  ||   !
    
    表达式 ? 代码1 : 代码2
    
  • Bit operations (understand) directly operate on binary [just heard about it]

    &  |   ^    ~    <<   >>   >>>
    

1.3 Statements

  • conditional judgment

    if () {
          
          } else {
          
          }
    
    if () {
          
          } else if () {
          
          } else {
          
          }
    
    switch () {
          
          
        case 1:
            break;
        case 2:
            break;
        default:
    }
    
  • cycle

    for
    
    while    do while
    
    for in//  let arr=[1,2,3,4,]
    
        //  for(let value of arr){
          
          
        //     console.log(value);
        //  }
    在遍历数组的时候的时候使用 for...of 
    for...in 循环出的是 key,for...of 循环出的是 value 
    
    for of
     const obj={
          
          
            a:1,
            b:2,
            c:3,
        }
    
         for(let key in obj){
          
          
               console.log(key);
         }
    推荐在循环对象属性的时候使用 for...in

1.4 Functions

  • Function writing
  • function return value
  • Function Parameters and Actual Parameters
  • Function parameter default values
  • function call

1.5 Built-in objects (class === constructor)

  • Array [*******************************]

    concat()   方法用于连接二个数组或多个数组
    
       const  arr=[1,2,3,]
       let arr1=['年后','聚会']
       let  arr3=arr.concat(arr1)
       console.log(arr3);
    every()   方法检测数组所有元素是否达到指定条件 
       
     const ages = [32, 33, 16, 40];
       function chackAdult(age){
          
          
           return age>18
       }
       
       let array=ages.every(chackAdult)
       console.log(array);
    filter()   过滤,把数组中满足条件的元素过滤出来放入一个新数组,返回这个新数组
     
        const ages = [32, 33, 16, 40];
    
        let ages1=ages.filter(function(v,i){
          
          
             return v>=32
         })
         console.log(ages1);
    
    find()  从数组中找到满足条件的第一个元素,把这个元素的值返回
     const hobs = ['html', 'css', '数组', 'MDN']
    
      const item=hobs.find((v,i)=>{
          
          
          //  console.log(v.length,i);
          return v.length===3
      })
      console.log(item);
    
    findIndex()  从数组中找到满足条件的第一个元素,把这个元素的索引返回
    const hobs = ['html', 'css', '数组', 'MDN']
    
      const item=hobs.findIndex((v,i)=>{
          
          
          //  console.log(v.length,i);
          return v.length===3
      })
      console.log(item);
    
    flat()     数组降维  
    
    const arr = [1, 2, [3, 4, [5, 6, [7, 8]]]] // 4 ---> 3  = 1
      // 数组降维
      const arr1=arr.flat(3)
      console.log(arr1);
    
    forEach()
    

Function: Loop, traverse each element in the array, and perform operations on each element of the array
Parameters: Callback function
Return value: None

const arr = [5, 12, 23, 54, 78, 99]
arr.forEach(fn)
function fn(a,b,c){ arr[b]=a+1 } console.log(arr); first The first parameter (a must be written) is the specific element of a being accessed (the content of the array traversed) the second parameter (b is optional) is the index of the element The third parameter (c is optional) is the array itself foreach will change the original array itself, no new array is produced









includes() Determines whether the array contains an element, if it does, return true, if not, return false

const arr = ['Xiao Diaochan', 'Zhao Zilong', 'Li Xunhuan']
console.log(arr.includes('Zhao Zilong'));
indexOf() Check the position of the element in the array, if not, return -1
const arr = ['a', 'b', 'c', 'd']
console.log(arr);
console.log(arr.indexOf('f'));
join() splits the array and divides the array according to the specified The delimiter, split into strings are separated by commas by default
const arr = ['html', 'css', 'js']
console.log(arr)
console.log( arr.join() ) // when nothing is written Parameters, separated by commas
console.log( arr.join(',') )
console.log( arr.join('/') )
console.log( arr.join('===') )

map() loops the array, passes in a callback function
to create a new array, and puts the return value of each loop into the new array, and finally returns the entire new array
const arr = ['a', 'b', 'c']
const result=arr.map(function(v,i){ // console.log(v); value of each item // console.log(i); index of each item return v.toUpperCase() }) console.log(result); pop() method removes the last element of the array, const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.pop(); push() to Add an element to the end of the array and return the new length const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; console.log(fruits.push(“Kiwi”)); reverse() reverses the array The order of const fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits.reverse()); shift() deletes the first element of the array slice() intercepts the array, Including the beginning, not including the end, if the second one is not written, it will be intercepted to the end
















const fruits = ["Banana", "Orange", "Apple", "Mango"]
console.log(fruits.slice(1, 3));
some() method detects whether any element of the array meets the specified condition
const ages = [ 32, 33, 16, 40];
function chackAdult(age){ return age>18 }

 let array=ages.some(chackAdult)
 console.log(array);

sort() array sort
array.sort(function (a, b) { return a - b // return b - a })

Notice:

  1. Write a - b, it is in ascending order, from small to large
  2. Write b - a, it is descending order, from big to small
    splice() is used to add or delete array elements, you can write three parameters, the first starts from the index, the second is to delete, and the third is to add
    const fruits = ["Banana" , "Orange", "Apple", "Mango"];
    console.log(fruits.splice(2, 2, "Lemon", "Kiwi"));
    unshift() Add the element to the beginning of the array, return the new length
    const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    console.log(fruits.unshift(“nihao”, “helloword”));
    The reduce() method accepts a function as an accumulator, Each value in the array (from left to right) starts to shrink and finally computes to a value.
    // parameter
    function (total, currentValue, index, arr){ // total must be preceded and // currentValue must be. Current loop element // currentIndex optional. The index of the current element // arr optional. The array object to which the current element belongs. }





- String [*******************************]

```js
charAt()   方法可返回指定索引位置的字符
// 字符串对象的方法
    // const str='我是一个字符串'
    // console.log(str.charAt(4));
    // console.log(str.charAt(str.length-1)); 取最后一个
charCodeAt() 返回字符串第一个字符的 Unicode 编码(H 的 Unicode 值):
     const str = "HELLO WORLD";
     console.log(str.charCodeAt(2));
concat()   方法用于连接二个字符串或多个字符串

const str1 = '你还是挺漂亮的'
    const str2 = '不!你不漂亮'
    const str3 = str1.concat(str2)
    console.log(str3);
includes()   用于判断字符串是否包含指定的子字符串,如果有TRUE,没有false
   const str = "Hello world, welcome to the Runoob。";
   console.log(str.includes('Runoob'));
indexOf()  返回指定字符串的值在字符串中第一个出现的位置  区分大小写
     const str = "Hello world, welcome to the Runoob。";
    console.log(str.indexOf('welcome'));
padEnd()  是在当前字符串的尾部填充字符串达到指定目标长度
padStart() 是在当前字符串的头部填充字符串达到指定目标长度
  const str = 'abcde'
   console.log(str.padStart(10));  //不传填充字符串默认用空格填充
   console.log(str.padStart(10,'*'));  //不传填充字符串默认用空格填充
   console.log(str.padStart(10,'js'));  //会重复填充字符串直到达到目标长度
   console.log(str.padStart(10,'javascript'));  //如果填充的字符串长度过长会发生截取,只填充左侧部分

repeat() 字符串复制指定次数
 const str='JAVA'
    console.log(str.repeat(2));
replace()  用于在一些字符串中用一些字符替换另一些字符,或替换正则匹配的表达式
  const str = 'JAVA Python'
    console.log(str.replace("JAVA", "C"));
slice(start,end)  返回一个字符串,内容为string的一个切片或子串。它不修改string。
start 参数字符串中第一个字符位置为 0, 第二个字符位置为 1, 以此类推,如果是负数表示从尾部截取多少个字符串,slice(-2) 表示提取原数组中的倒数第二个元素到最后一个元素(包含最后一个元素)。
end 参数如果为负数,-1 指字符串的最后一个字符的位置,-2 指倒数第二个字符,以此类

split() 方法用于把一个字符串分割成字符串数组。
 const str = "Hello world!";
        console.log(str.slice(0, 3));
        console.log(str.slice(-1));
        console.log(str.slice(-2));
substr() 方法可在字符串中抽取从 开始 下标开始的指定数目的字符。

提示: substr() 的参数指定的是子串的开始位置和长度,因此它可以替代 substring() 和 slice() 来使用。
  const str = "Hello world!";
    console.log(str.substr(2, 5));
    console.log(str.substring(2, 5));//包括开始处的字符,不不结束的字符

substring() 方法返回的子串包括开始处的字符,但不结束处的字符。
toLowerCase() 把字符串转换为小写
toUpperCase() 把字符串转换为大小
trim()  方法用于删除字符串的头尾空白符 (空格,制表符,换行) 不会改变原始字符串
 const str = "        Runoob        ";
    console.log(str.trim());
  • Date

    getFullYear()getMonth()getDate()getHours()getMinutes()getSeconds()getTime() 时间戳 
      //    返回 190 年 1 月 1 日之间的间隔月数:
        const date=new Date()
        console.log(date.getTime());
    
  • Math

    abs() 绝对值
    ceil()  向上取整
    floor() 向下取整
    max() 最大值
    min() 最小值
    random() 随机数
    round() 四舍五入
    
  • Object

    Object.keys()    获取对象所有的键名,主要用于循环对象
    object.values() 用于获取所有对象的属性值 
    const data={
          
          
            name:"张三",
            age:18
        }
        Object.keys(data).forEach(function(key){
          
          
              console.log(key,name[key]);
        })
    
    let person = {
          
           name:'张三', age: 25, address:'深圳', getName: ()=> console.log('我是谁')}
    
            console.log(Object.keys(person).join()); // [“name”, “age”, “address”,“getName”]
    
    Object.assign()   合并对象,如果对象的key键名相同,后面覆盖前面
    拷贝对象
    
    // 三个对象
            const user1 = {
          
          
                name: '小貂蝉',
                age: 18
            }
    
            const user2 = {
          
          
                name: '李逵',
                email: '[email protected]'
            }
    
            const user3 = {
          
          
                name: '关羽',
                sex: '男'
            }
    
            let result=Object.assign({
          
          },user1,user2,user3)
            console.log("合并的对象",result);
    
    
  • Number

    toFixed() 可把数字四舍五入为指定小数照射的方法数字
    

1.6 Basic operations on arrays and objects

数组[索引] 
对象.属性           console.log(user1.getname());
                    

对象['属性']       console.log(user1['name']);

2 DOM [understand]

Function: do whatever you want for dom nodes

2.1 increase

document.createElement('标签')  
document.appendChild()
dom.textContent = '内容'
dom.innerHTML = '内容'

2.2 delete

dom.remove()
dom.textContent = ''
dom.innerHTML = ''

2.3 change

dom.textContent = '新的值'
dom.innerHTML = '新的值'

2.4 check

document.getElementById()
document.querySelector()
document.querySelectorAll()

2.5 Operation of attributes

dom.style.属性 = '新的值'
dom.属性 = '新的值'
dom.className = '类名'
dom.dataset.属性 = '新的值'  自定义属性
dom.setAttribute('属性名', '属性值')
dom.getAttribute('属性名')

2.6 Events

dom.addEveventListener(事件类型, function () {
    
    
    
})

# 事件类型
UI事件
	load  
    unload 
    onunload 事件在用户退出页面时发生。
    onunload 发生于当用户离开页面时发生的事件(通过点击一个连接,提交表单,关闭浏览器窗口等等。) 
     resize  当浏览器窗口被调整到一个新的高度或宽度时,就会触发resize事件
     scroll
     scrollTop
解释:元素滚动条内的顶部隐藏部分的高度。

scrollTop属性只有DOM元素才有,window/document没有。

用法1:获取值 var top = element.scrollTop;//返回数字,单位像素

用法2:设置值 element.scrollTop = 200;

对上面的例子来说,控制滚动条的位置是wrap.scrollTop=xx;而不是inner.scrollTop,道理同上。


scrollHeight
解释:元素滚动条内的内容高度。
scrollHeight同scrollTop属性一样,只有DOM元素才有,window/document没有。
不同的是scrollHeight是只读,不可设置。
document.body.scrollHeight获得。
此外还有scrollLeft,scrollWidth,道理是一样的。 

scrollWidth
scrollWidth = width(自身实际长度,包括不可见区) + padding + border + margin
scrollHeight = height(自身实际高度,包括不可见区) + padding + border + margin
     
焦点事件
	focus  输入框获取焦点
    blur   输入框失去焦点
鼠标事件 
类型	事件
click	单击鼠标左键时发生,如果右键也按下则不会发生
dbclick	双击鼠标左键时发生,如果右键也按下则不会发生
mousedown	单击任意一个鼠标按钮时发生
mouseout	鼠标指针位于某个元素上且将要移出元素的边界时发生
mouseover	鼠标指针移出某个元素到另一个元素上时发生
mouseup	松开任意一个鼠标按钮时发生
mousemove	鼠标在某个元素上时持续发生
    
滚轮事件
	scroll
键盘事件
	keydown  
    keypress
    keyup

3 BOM [understand]

Function: Do whatever you want with the browser

3.1 location

href  //完整地址 进行跳转
origin //协议 ip域名  端口
host //ip域名 端口
hostname  //ip 域名
port // 端口号
pathname //路径
search //地址栏的参数
hash //描点
protocol  	//协议

reload() //刷新 

3.2 window

window.setTimeout() 
方法:
        周期定时器:   多少毫秒执行一次(多次执行)
            let 定时器名 = setInterval(function(){
    
     多次执行的代码 },毫秒值) 
            let 定时器名 = setInterval(函数名,毫秒值)  
        停止周期定时器:
            clearInterval( 定时器名 )

        超时定时器:  隔多少毫秒之后才执行一次(执行1)
            let 定时器名 = setTimeout( 匿名函数, 毫秒值)
            let 定时器名 = setTimeout( 函数名,毫秒值)
        停止超时定时器:
            clearTimeout( 定时器名 )
window.setInterval()
window.alert()  警告框
window.open([URL], [窗口名称], [参数字符串])
URL:可选参数,在窗口中要显示网页的网址或路径。如果省略这个参数,或者它的值是空字符串,那么窗口就不显示任何文档。
window.onscroll = function () {
    
    }   //页面滚动条事件

<script>
    // 页面加载完毕加载
    window.addEventListener('load', function () {
    
    
 
    })
    // 只需要加载成功元素就可以
    window.addEventListener('DOMContentLoaded', function () {
    
    
 
    })
    // 只要窗口大小发生像素变化就会触发
    window.addEventListener('resize', function () {
    
    
    // 当前窗口宽度
    console.log(window.innerWidth);
    })
</script>

3.3 history

go(n) 前进 后退也可以
forward()  前进
back() 后退

3.4 screen

width 屏幕宽度
height 屏幕高度

3.5 navigator

userAgent  获取浏览器信息(类型及系统)
language 语言



##3.6 本地存储

localstorage(永久保存)&&sessionstorage(重新打开浏览器会消失)

sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。而localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。

localStorage和sessionStorage都具有相同的操作方法,例如setItem、getItem和removeItem等

setItem存储value

用途:将value存储到key字段

用法:.setItem( key, value)

getItem获取value

用途:获取指定key本地存储的值

用法:.getItem(key)

removeItem删除key

用途:删除指定key本地存储的值

用法:.removeItem(key)

clear清除所有的key/value

用途:清除所有的key/value

用法:.clear()

sessionStorage和localStorage提供的key()和length可以方便的实现存储的数据遍历

2 Logic [understand, train slowly]

  • Create a warehouse and write a small function every few days using native js
    • Tab
    • countdown
    • Back to top
    • Carousel switch
    • floor scrolling
    • Loop rendering
  • Summarize the steps to write each function
  • As long as there is a similar function in the future, you can find this step and write it according to the step.

Guess you like

Origin blog.csdn.net/qq_53461589/article/details/130650005