JS基本用法汇总(持续更新...)


前言

一个小菜鸡的JS日常使用总结

一、数组篇

1. some

JavaScript Array some() 方法 用于检测数组中的元素是否满足指定条件(函数提供)。

some() 方法会依次执行数组的每个元素:
如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
如果没有满足条件的元素,则返回false。

例子:判断数组中是否存在重复元素:

let a = [1, 2, 3];
let result = a.some((el, index, arr) => {
    return arr.indexOf(el) !== index;
});
console.log(result);

运行结果:
false

let a = [1, 2, 2, 3];
let result1 = a.some((el, index, arr) => {
    return arr.indexOf(el) !== index;
});
console.log(result1);

运行结果:
true

2. map和reduce

JavaScript Array map() 方法 :返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。不会改变原数据

let array = [1, 2, 3];
let result = array.map((x) => {
    return x * x;
});
console.log(array);
console.log(result);

运行结果:
[1, 2, 3]
[1, 4, 9]

例子:把数字数组全部转化成字符串数组

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr);
arr = arr.map(String);
console.log(arr);

运行结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”]

例子:格式化字符串数组,规格:首字母大写,其他小写

/**
 * 输入:['asdD','edGs','PHD']
 * 输出:['Asdd','Edgs','Phd']
 * 规格首字母大写,其他小写
 */
function formatStrArr(arr) {
    return arr.map((x) => {
        return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase();
    });
}

console.log(formatStrArr(["asdD", "edGs", "PHD"]));

运行结果:
[“Asdd”, “Edgs”, “Phd”]

JavaScript reduce() 方法:接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
可以做累积、累加等其他规则的累计计算器。

let arr1 = [1, 2, 3, 4, 5, 7, 6];
let arr1Rlt = arr1.reduce((x, y) => {
    return x * 10 + y;
});
console.log(arr1);
console.log(arr1Rlt);

运行结果:
[1, 2, 3, 4, 5, 7, 6]
1234576

例:讲一个字符串转化成数字。 不要使用内置函数

function str2int(s) {
    let strArr = [...s];
    strArr = strArr.map((x) => {
        return +x;
    });
    return strArr.reduce((x, y) => {
        return x * 10 + y;
    });
}
console.log(str2int("234"),typeof  str2int("234"));

运行结果:
234 “number”

3. filter

JavaScript Array filter() 方法 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。—过滤器

注:空数组不会检查,并且不会改变原数组。

例:数组去重
思路:过滤掉indexOf判断的元素位置和index本身位置不相等的元素。

let a = [1, 2, 3, 3];
let b = a.filter((el, index, arr) => {
    return arr.indexOf(el) === index;
});
console.log(b);

运行结果:
[1, 2, 3]

例:过滤掉字符串数组中的空串

let array1 = ["a", "", "dFG", "", "asdf", "hello world"];
let filterRlt = array1.filter((el, index, arr) => {
    return el && el.trim();
});
console.log(filterRlt);

运行结果:
[“a”, “dFG”, “asdf”, “hello world”]

4.sort

JavaScript sort() 方法 根据ASCII编码排序,需要定义排序函数,按照函数规则排序 。修改原数组

该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:
若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
若 a 等于 b,则返回 0。
若 a 大于 b,则返回一个大于 0 的值。

例子:从小到大排列

let sortArr = [1, 23, 4, 6, 90];
sortArr.sort((a, b) => {
    return a - b;
});
console.log(sortArr);

运行结果:
[1, 4, 6, 23, 90]

例子:从大到小排列

let sortArr = [1, 23, 4, 6, 90];
sortArr.sort((a, b) => {
    return b - a;
});
console.log(sortArr);

运行结果:
[90, 23, 6, 4, 1]

5.every

JavaScript Array every() 方法 用于检测数组所有元素是否都符合指定条件(通过函数提供)。
注意 :区分some函数,用于检测数组中的元素是否满足指定条件(函数提供)。

every:所有元素都满足条件,返回true,只要有一个不满足(false), 则返回false。
some:如果有一个元素满足条件,返回true,全部不满足,则返回false。

例子:

let newArr = [1, 34, 6, 7, 8, 99, 4];
let everyRlt = newArr.every((el, index, arr) => {
    return el > 3;
});
let someRlt = newArr.some((el, index, arr) => {
    return el > 3;
});
console.log(everyRlt);
console.log(someRlt);

运行结果:
false
true

6. find和findIndex

find() 方法 返回通过测试(函数内判断)的数组的第一个元素的值。没有符合条件的元素返回 undefined
findIndex() 方法 返回传入一个测试条件(函数)符合条件的数组第一个元素位置。没有符合条件的元素返回 -1

let personArr = [{ name: "zhangSan", age: 23 }, { name: "liSi", age: 30 }];
let person = personArr.find((el, index, arr) => {
    return el.age === 23;
});
let personIdx = personArr.findIndex((el, index, arr) => {
    return el.age === 23;
});
console.log(person);
console.log(personIdx);

运行结果:
{name: “zhangSan”, age: 23}
0

7. fill

ES6语法,快速便捷的初始化一个数组 ,但要初始化的数组需要给定初始长度。

例如:

给定长度为0的数组,并试图填充元素1,结果为:[]

 let arr = [];
 arr.fill(1);
console.log(arr);
//  []

给定长度已知为5的数组,并填充元素1,结果为:[1,1,1,1,1]

let arr = [1, 2, 3, 4, 5];
arr.fill(1);
console.log(arr);
// [1, 1, 1, 1, 1]

还可以这样:可任意长度填充 或 指定位置填充

let arr = new Array(5).fill(10);
 console.log(arr);
 // [10, 10, 10, 10, 01]

或者

let arr = Array(5).fill(1);
console.log(arr);
// [1, 1, 1, 1, 1]

或者
let arr = Array(5).fill(1, 2, 4); //填充数组的第3 、4 个元素
console.log(arr);
// [empty × 2, 1, 1, empty]

想一想:
如何快速初始化一个长度为10,元素从1-10的数组 。
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

答案:

Array(10).fill(null).map((_, index) =>  index + 1);

二、对象篇

1. 判断自身属性是否存在

let obj = {
    a: "a",
    b: "b"
};
console.log(obj.hasOwnProperty('a'));    //true
console.log(obj.hasOwnProperty('c'));    //false

JavaScript 并没有保护 hasOwnProperty 属性名,因此,可能存在于一个包含此属性名的对象。

let object = {
	a:"a",
	hasOwnProperty:function(){
		return false;
	}
}
console.log(object.hasOwnProperty('a'));     //false
console.log(object.hasOwnProperty('c'));     //false
console.log(object.hasOwnProperty());       //false

如上代码,任何属性判断返回都为false。可以通过使用原型链上的hasOwnProperty 方法解决

let object = {
    a: "a",
    hasOwnProperty: function() {
        return false;
    }
};
let result = Object.prototype.hasOwnProperty.call(object, "a");
console.log(result);   //true

2. 原型继承

现在有两个对象,Animal和 Dog,我们希望 Dog 由 Animal 拓展而来,即:Dog继承于Animal。

Animal对象定义:

function Animal(name) {
    this.name = name;
    this.run = function() {
        return this.name + " running";
    };
}

Dog对象定义:

function Dog(name) {
    this.say = function() {
        return this.name + " said";
    };
}

我们验证其原型链:

let a = new Animal("动物");
let d = new Dog("狗");
console.log(a.__proto__ === Animal.prototype);  //true
console.log(a.__proto__.__proto__ === Object.prototype); //true
console.log(d.__proto__ === Dog.prototype);  //true
console.log(d.__proto__.__proto__ === Object.prototype); //true

由此可见原型关系为如下,二者最终的原型都是Ojbect.prototype, 互相之间没有继承关系。

new Animal() --> Animal.prototype --> Object.prototype ;
new Dog() --> Dog.prototype --> Object.prototype ;

通过上面简单说明,相信大家都能猜出那么正确的原型关系:
new Dog() --> Dog.prototype --> Animal.prototype --> Object.prototype ;
那么我们只要实现这种原型关系即可。

首先,我们修改Dog对象,在Dog对象中调用Animal的构造函数:

function Dog(name) {
    Animal.call(this, name); //调用Animal构造函数 Animal.apply(this, name);
    this.say = function() {
        return this.name + " said";
    };
}

此时我们调用Animal中的方法试试:

let xg = new Dog("小狗");
console.log(xg.run()); //小狗 running

很开心有没有,能调用Animal中的run方法了,那是不是实现继承了呢,我们验证一下:

console.log(xg.__proto__ === Dog.prototype); //true
console.log(xg.__proto__.__proto__ === Animal.prototype); //false

可以看出,原型关系还是不对。

这样不行 我直接把Dog的原型指向Animal,

Dog.prototype = Animal.prototype;

继续验证:

console.log(xg.__proto__ === Dog.prototype); //true
console.log(xg.__proto__.__proto__ === Animal.prototype); //false

还是不行… ^-^

调用构造函数不行,直接共享原型也不行,那么我们借助中间量作为中介转一下可不可以?

//空对象
function F() {
}
F.prototype = Animal.prototype;
Dog.prototype = new F();
Dog.prototype.constructor = Dog;

感觉很完美,那么我们验证:

let xb = new Dog("xiao bai");
console.log('开始验证:');
console.log(xb.__proto__ === Dog.prototype); //true
console.log(xb.__proto__.__proto__ === Animal.prototype); //true
console.log(xb.__proto__.__proto__.__proto__ === Object.prototype); //true
console.log(xb instanceof Animal);//true
console.log(xb instanceof Dog); // true

在这里插入图片描述

啧啧啧,验证也很完美,完美的原型链。至此已实现原型继承。完整代码如下:

function Animal(name) {
    this.name = name;
    this.run = function() {
        return this.name + " running";
    };
}

function Dog(name) {
    Animal.call(this, name);//调用Animal构造函数 Animal.apply(this, name);
    this.say = function() {
        return this.name + " said";
    };
}

//空对象
function F() {
}

F.prototype = Animal.prototype;
Dog.prototype = new F();
Dog.prototype.constructor = Dog;

let xb = new Dog("xiao bai");
console.log("开始验证:");
console.log(xb.__proto__ === Dog.prototype); //true
console.log(xb.__proto__.__proto__ === Animal.prototype); //true
console.log(xb.__proto__.__proto__.__proto__ === Object.prototype); //true
console.log(xb instanceof Animal);//true
console.log(xb instanceof Dog); // true

附加:另一种实现继承的方式,es6语法class。

class Car {
    constructor(name) {
        this.name = name;
    }

    run() {
        console.log("Car Running");
    };

}

class SmallCar extends Car {
    constructor(name) {
        super(name);
    }

    run() {
        super.run();
        console.log("SmallCar Running");
    }
}

let a = new Car("haha");
let b = new SmallCar("haha");
console.log(b.__proto__ === SmallCar.prototype);//true
console.log(b.__proto__.__proto__ === Car.prototype);//true
console.log(b.__proto__.__proto__.__proto__ === Object.prototype);//true

总结

随笔一记,从小小菜鸡变小菜鸡!!!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hui-1018

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值