Skip to content

JS小问题集 持续更新

简述

工作中遇到的很多小问题,解决了但是疏于整理,导致重复问题重复仍需百度搜索,特有此记录小问题。

方法函数

split

不在自身操作

reverse

在自身操作

replace

替换不在自身操作,而是返回替换后的结果

splice

删除数组某一元素:Array.splice(index,howmany) ,传索引和1,返回被删除的数组

添加:Array.splice(index,howmany,'…')

在自身操作

Object.assign(target, ...objects)

将对象合并到target上,如果有相同的属性,后面的会覆盖掉前面的值

promise.all

异步请求返回Promise 假设有 a,b,c三个promise Promis.all([a,b,c]).then(() v=>{})

.call()

通过 call(),能够使用属于另一个对象的方法。

js
var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName:"Bill",
    lastName: "Gates",
}
person.fullName.call(person1);  // 将返回 "Bill Gates"

Object.prototype.toString.call()

使用Object的toString()去检测类型,由于Array,Function等Object子类重写了toString,所以无法判断具体的类别。该方案可以区别null Array Object等类型

js
console.log(Object.prototype.toString.call("jerry"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]

argument

函数内置的变量,方法传入的参数都在这里面存储,可以根据argument的长度实现方法重载

JS 各种循环性能对比

普通 for 循环 > forEach > for of > map > for in

i++ 与 i+=1 对循环无明显影响, while 与 for 效率差不多

JSON.parse JSON.stringify 报错

JSON.parse 对能转换的字符串有严格的格式要求,如果字符串不符合,则会报错,在进行深拷贝时,两者一起使用可以达到一个快速拷贝的效果,但也有时候会因为对象嵌套对象导致无法转换,目前只能通过tryCatch避免报错,另一方面,parse与stringify都有第二个参数,在转换时可以拿到每个属性进行操作。

JSON.stringify 在转换时,如果被转换的属性值有toJSON()方法,那么会直接使用toJSON方法去序列化(即转字符串)当前属性值

js
JSON.parse('{"p": 5}', function (k, v) {
    if(k === '') return v;     // 如果到了最顶层,则直接返回属性值,
    return v * 2;              // 否则将属性值变为原来的 2 倍。
});                            // { p: 10 }

JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) {
    console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的,
                    // 最后一个属性名会是个空字符串。
    return v;       // 返回原始属性值,相当于没有传递 reviver 参数。
});

// 1
// 2
// 4
// 6
// 5
// 3
// ""
var obj = {
  foo: 'foo',
  toJSON: function () {
    return 'bar';
  }
};
JSON.stringify(obj);      // '"bar"'
JSON.stringify({x: obj}); // '{"x":"bar"}'

方法重载与多态

重载,指的是一个作用域下,多个方法有同样的方法名,但是参数列表不同 多态,指同一方法,在不同对象去执行时,产生的结果不一样 重写,子类继承父类,子类将父类已有方法重新定义 在js中,我们没法像Java那样,在一个类下写多个相同名称的方法,所以需要根据参数在方法内部进行判断,执行不同操作,可以通过argument获取参数列表的长度,也可以判断参数类型执行不同操作

worker sharedworker

function 内部this指向

谁在调用这个方法,谁就是this

js
  function test(){
    console.log(this)
  }
  const test2 ={
    name:'test',
    test2: function(){
      console.log(this)
    }
  }
  function test3(){
    this.test33 = '123'
    console.log(this)
  }
  test() // Window
  test2.test2() //test2
  test3() // Window 执行时还把test33挂在了Window上

类型

Uint8Array int8Array

带U的均是无符号的,既取值范围只能是0以上

null

js
typeof null  // "object"
null instanceof Object // false

typeof null返回object,这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来

js
null == undefined // true
null === undefined // false

样式

svg中的style样式

据说如果style如果被更改,会触发所有svg中相同class的更新事件,造成性能损耗,具体有待考证。

元素之间的缝隙

网上有一说是代码空格所致,我遇到此问题是因为循环排列图片,图片之间有一个缝隙,于是设置其父元素font-size 为0解决了这个问题

监听dom元素宽高变化

js
      const dom = document.getElementById(id)
      const resizeObserver = new ResizeObserver((entries) => {
      // 当DOM元素的宽高发生变化时执行回调函数
        console.log('-----------------resize-----------------')
        console.log('resize', entries)
        document.getElementById('threeContainer').style.height = `${entries[0].contentRect.height}px`
        resize()
      })
      resizeObserver.observe(dom);
      // 注销
      resizeObserver.disconnect();

取消ios长按呼出的系统操作(复制,等等)

css
-webkit-touch-callout: none;

取消选中文本

css
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;

倾斜元素

css
transform: skewX(-20deg); /* 沿X轴倾斜-20度 */

更新于:

夜茶 2020 ~ 2026