分享

不可错过的一些 js小技巧

 LGPL 2023-05-04 发布于北京

1. 获取指定范围内的随机整数

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

2. 打乱数组顺序

let arr:[31,2,3,'排序','😄']
arr = arr.sort(() => 0.5 - Math.random())
//  [ 3, 2, "😄", "排序", 31 ]

3. 用Math.max()取数组最大值

let arrr = [ 6, 1, 2, 8, 10 ] 
// ES5 的写法
let max = Math.max.apply(Math,arr) 
Math.max.apply(null, arrr)
// ES6使用拓展运算符的写法
Math.max(...arr)
// max = 10

// 等同于
Math.max(14, 3, 77);

3. 去除数字之外的所有字符

var str = ''yannnianjunzi,温其如玉,一个亿,1000000000😄"
let num = str.replace(/\D/g,'')
// num 1000000000

3.1 replaceAll方法

const str = "hello world";
// 之前
str.replace(/o/g, "a")// "hella warld"
// 现在
str.replaceAll("o", "a")// "hella warld"

4. 反转字符串或者单词

let str = 'dfvgwsdfgg,奋斗奋斗参考看看,dsfgf'
let reverseStr = str.split('').reverse().join('')

5. 将十进制转换为二进制或十六进制

let num = 12;
let num1 = Number(this.num10).toString(2)
let num2 = Number(this.num10).toString(16)

6. 如何检查对象中是否存在某个属性

6.1 第一种使用 in 操作符号:

const o = { 
  "prop" : "bwahahah",
  "prop2" : "hweasa"
};
 
console.log("prop" in o); // true
console.log("prop1" in o); // false

6.2 使用 hasOwnProperty 方法,hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)

6.2.1 Object.hasOwn()和Object.hasOwnProperty区别 JavaScript 对象的属性分成两种:自身的属性和继承的属性。对象实例有一个hasOwnProperty()方法,可以判断某个属性是否为原生属性。ES2022 在Object对象上面新增了一个静态方法Object.hasOwn(),也可以判断是否为自身的属性。Object.hasOwn()可以接受两个参数,第一个是所要判断的对象,第二个是属性名。

const foo = Object.create({ a: 123 });
foo.b = 456;

Object.hasOwn(foo, 'a') // false
Object.hasOwn(foo, 'b') // true

上面示例中,对象foo的属性a是继承属性,属性b是原生属性。Object.hasOwn()对属性a返回false,对属性b返回true。
Object.hasOwn()的一个好处是,对于不继承Object.prototype的对象不会报错,而hasOwnProperty()是会报错的。

console.log(o.hasOwnProperty("prop2")); // true
console.log(o.hasOwnProperty("prop1")); // false
const obj = Object.create(null);

obj.hasOwnProperty('foo') // 报错
Object.hasOwn(obj, 'foo') // false
// 上面示例中,Object.create(null)返回的对象obj是没有原型的,不继承任何属性,
// 这导致调用obj.hasOwnProperty()会报错,但是Object.hasOwn()就能正确处理这种情况。

6.3 第三种使用括号符号obj["prop"]。如果属性存在,它将返回该属性的值,否则将返回undefined。

console.log(o["prop"]); // "bwahahah"
console.log(o["prop1"]); // undefined

7.生成一个长度为100并且内容为0的数组

1. new Array(100).fill(0); Array(100).fill(0)
2. Array.from({length:100}, x => x=0)
3. Array.apply(null, {length:100} ).map(x => x=0)
1.png

2.png

3.png

Array.from()还可以接受一个函数作为第二个参数,作用类似于数组的map()方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]

8. 通过toString来检测各种数据类型

/**
* @description: 数据类型的检测
* @param {any} data 要检测数据类型的变量
* @return {string} type 返回具体的类型名称【小写】
*/
const isTypeOf = (data) => {
    return Object.prototype.toString.call(data).replace(/\[object (\w+)\]/, '$1').toLowerCase()
}

console.log(isTypeOf({})) // object
console.log(isTypeOf([])) // array
console.log(isTypeOf("ss")) // string
console.log(isTypeOf(1)) // number
console.log(isTypeOf(false)) // boolean
console.log(isTypeOf(/w+/)) // regexp
console.log(isTypeOf(null)) // null
console.log(isTypeOf(undefined)) // undefined
console.log(isTypeOf(Symbol("id"))) // symbol
console.log(isTypeOf(() => { })) // function

**9.递归求数组的和

getRecursionList(list){
  function getSum(i)  {
    return i >= list.length ? 0 : list[i] +  getSum(i+1)
}
// return getSum(0)  // getSum(0) 相当于调用了这个函数
return getSum(0)
}

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多