哥伦布

JavaScript常用内置方法

复制代码
1.some()
2. reduce()
3. Every()
4. map()
5. flat()
6. filter()
7. forEach()
8. findIndex()
9. find()
10. sort()
11. concat()
12. fill()
13. includes()
14. reverse()
15. flatMap()
复制代码

1、some()--- 有一个相同时

此方法为参数传递的函数测试数组。如果有一个元素与测试元素匹配,则返回true,否则返回false。

译者注: some() 不会对空数组进行检测;some() 不会改变原始数组。

1 const myAwesomeArray = ["a", "b", "c", "d", "e"]
2 myAwesomeArray.some(test => test === "d")
3 //-------> Output : true

2、reduce()

此方法接收一个函数作为累加器。它为数组中的每个元素依次执行回调函数,不包括数组中被删除或者从未被赋值的元素。函数应用于累加器,数组中的每个值最后只返回一个值。

译者注:reduce() 方法接受四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组。

1 const myAwesomeArray = [1, 2, 3, 4, 5]
2 myAwesomeArray.reduce((total, value) => total * value)
3 // 1 * 2 * 3 * 4 * 5
4 //-------> Output = 120

3、Every()--- 每一个相同时

此方法是对数组中每项运行给定函数,如果数组的每个元素都与测试匹配,则返回true,反之则返回false。

1 const myAwesomeArray = ["a", "b", "c", "d", "e"]
2 myAwesomeArray.every(test => test === "d")
3 // -------> Output : falseconst myAwesomeArray2 = ["a", "a", "a", "a", "a"]
4 myAwesomeArray2.every(test => test === "a")
5 //-------> Output : true

4、map()--- 返回一个新数组

该方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。它按照原始数组元素顺序依次处理元素。

译者注:map() 不会对空数组进行检测;map() 不会改变原始数组。

1 const myAwesomeArray = [5, 4, 3, 2, 1]myAwesomeArray.map(x => x * x)
2 //-------> Output : 25
3 //                  16
4 //                  9
5 //                  4
6 //                  1

5、flat()--- 二维转一维

此方法创建一个新数组,其中包含子数组上的holden元素,并将其平整到新数组中。请注意,此方法只能进行一个级别的深度。

1 const myAwesomeArray = [[1, 2], [3, 4], 5]
2 myAwesomeArray.flat()
3 //-------> Output : [1, 2, 3, 4, 5]

6、filter()--- 过滤出符合条件的数组

该方法接收一个函数作为参数。并返回一个新数组,该数组包含该数组的所有元素,作为参数传递的过滤函数对其返回true。

译者注:filter()方法是对数据中的元素进行过滤,也就是说是不能修改原数组中的数据,只能读取原数组中的数据,callback需要返回布尔值;为true的时候,对应的元素留下来;为false的时候,对应的元素过滤掉。

1 const myAwesomeArray = [  { id: 1, name: "john" },  
2 { id: 2, name: "Ali" },  { id: 3, name: "Mass" },  
3 { id: 4, name: "Mass" },]
4 myAwesomeArray.filter(element => element.name === "Mass")
5 //-------> Output : 0:{id: 3, name: "Mass"},
6 //                  1:{id: 4, name: "Mass"}

7、forEach()--- 遍历

此方法用于调用数组的每个元素。并将元素传递给回调函数。译者注: forEach() 对于空数组是不会执行回调函数的。

1 const myAwesomeArray = [  { id: 1, name: "john" },  
2 { id: 2, name: "Ali" },  { id: 3, name: "Mass" },]
3 myAwesomeArray.forEach(element => console.log(element.name))
4 //-------> Output : john
5 //                  Ali
6 //                  Mass

8、 findIndex()--- 返回元素索引值

此方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。

它为数组中的每个元素都调用一次函数执行,当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。如果没有符合条件的元素返回 -1

译者注:findIndex() 对于空数组,函数是不会执行的, findIndex() 并没有改变数组的原始值。

1 const myAwesomeArray = [  { id: 1, name: "john" },  
2 { id: 2, name: "Ali" },  { id: 3, name: "Mass" },]myAwesomeArray.findIndex(element => element.id === 3)// -------> Output : 2myAwesomeArray.findIndex(element => element.id === 7)//-------> Output : -1

9、 find()--- 返回元素

此方法返回通过测试(函数内判断)的数组的第一个元素的值。find() 方法为数组中的每个元素都调用一次函数执行:当数组中的元素在测试条件时回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。如果没有符合条件的元素返回 undefined。

译者注: find() 对于空数组,函数是不会执行的;find() 并没有改变数组的原始值。

1 const myAwesomeArray = [  { id: 1, name: "john" }, 
2  { id: 2, name: "Ali" },  { id: 3, name: "Mass" },]
3  myAwesomeArray.find(element => element.id === 3)
4  // -------> Output : {id: 3, name: "Mass"}
5  myAwesomeArray.find(element => element.id === 7)
6  //-------> Output : undefined

10、 sort()--- 排序

此方法接收一个函数作为参数。它对数组的元素进行排序并返回它。也可以使用含有参数的sort()方法进行排序。

1 const myAwesomeArray = [5, 4, 3, 2, 1]
2 // Sort from smallest to largestmyAwesomeArray.sort((a, b) => a - b)
3 //  -------> Output : [1, 2, 3, 4, 5]
4 // Sort from largest to smallestmyAwesomeArray.sort((a, b) => b - a)
5 //-------> Output : [5, 4, 3, 2, 1]

11、 concat()--- 连接数组

此方法用于连接两个或多个数组/值,它不会改变现有的数组。而仅仅返回被连接数组的一个新数组。

const myAwesomeArray = [1, 2, 3, 4, 5]const 
myAwesomeArray2 = [10, 20, 30, 40, 50]
myAwesomeArray.concat(myAwesomeArray2)
//-------> Output : [1, 2, 3, 4, 5, 10, 20, 30, 40, 50]

12、 fill()--- 替换目标元素

此方法的作用是使用一个固定值来替换数组中的元素。该固定值可以是字母、数字、字符串、数组等等。它还有两个可选参数,表示填充起来的开始位置(默认为0)与结束位置(默认为array.length)。

译者注:fill() 方法用于将一个固定值替换数组的元素。

复制代码
1 const myAwesomeArray = [1, 2, 3, 4, 5]
2 // The first argument (0) is the value
3 // The second argument (1) is the starting index
4 // The third argument (3) is the ending indexmyAwesomeArray.fill(0, 1, 3)
5 //-------> Output : [1, 0, 0, 4, 5]
arr.fill(value, start, end-1)
 
复制代码

13、 includes()--- es6判断元素是否包含在数组

 同比es5的indexOf()--- 有对应值返回索引,无则返回-1

此方法用于判断字符串是否包含指定的子字符串。如果找到匹配的字符串则返回 true,否则返回 false。
译者注:includes() 方法区分大小写。

1 const myAwesomeArray = [1, 2, 3, 4, 5]
2 myAwesomeArray.includes(3)
3 // -------> Output : truemyAwesomeArray.includes(8)
4 // -------> Output : false

14、 reverse()--- 颠倒数组

此方法用于颠倒数组中元素的顺序。第一个元素成为最后一个,最后一个元素将成为第一个。

1 const myAwesomeArray = ["e", "d", "c", "b", "a"]
2 myAwesomeArray.reverse()
3 // -------> Output : ['a', 'b', 'c', 'd', 'e']

15、 flatMap()

该方法将函数应用于数组的每个元素,然后将结果压缩为一个新数组。它在一个函数中结合了flat()和map()。

1 const myAwesomeArray = [[1], [2], [3], [4], [5]]
2 myAwesomeArray.flatMap(arr => arr * 10)
3 //-------> Output : [10, 20, 30, 40, 50]
4 // With .flat() and .map()myAwesomeArray.flat().map(arr => arr * 10)
5 //-------> Output : [10, 20, 30, 40, 50]

序:js中常用方法总结

JavaScript中常用方法

Array

new Set()

用来对数组进行去重。

const arr = [3,4,4,5,4,6,5,7];
console.log(new Set(arr)); // {3,4,5,6,7}
const a = Array.from(new Set(arr)) // [3, 4, 5, 6, 7]

sort()

对数组元素进行排序(改变原数组)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.sort()) // [3, 4, 4, 4, 5, 5, 6, 7]

reverse()

反转数组中的元素(改变原数组)。

const arr = [3,4,4,5,4,6,5,7];
conosle.log(arr.reverse());  // [7, 6, 5, 5, 4, 4, 4, 3]

delete

删除一个数组成员,会形成空位,并不会影响length属性(改变原数组),同样适用于对象。

//数组
const arr = [3,4,4,5,4,6,5,7];
delete arr[1];
conosle.log(arr);  // [3, empty, 4, 5, 4, 6, 5, 7]

//对象
const obj = {name'pboebe',age'23',sex'女'};
delete obj.sex;
console.log(obj);  // {name: "pboebe", age: "23"}

shift()

把数组的第一个元素从其中删除,并返回第一个元素的值(改变原数组)。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.shift(); 
console.log(arr);  // 3
// [empty, 4, 5, 4, 6, 5, 7]

unshift()

向数组的起始处添加一个或多个元素,并返回新的长度(改变原数组)。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.unshift(8);
console.log(a);  // 9(a为返回的数组的新长度)
console.log(arr); // [8, 3, 4, 4, 5, 4, 6, 5, 7]

push()

在数组的末端添加一个或多个元素,并返回添加新元素后的数组长度(改变原数组)。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.push(8,9);
console.log(a); // 10(a为返回的数组的新长度)console.log(arr); 
// [3, 4, 4, 5, 4, 6, 5, 7, 8, 9]

valueOf()

返回数组本身。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.valueOf()); // [3,4,4,5,4,6,5,7]

toString()

可把值转换成字符串。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.toString()); // 3,4,4,5,4,6,5,7

concat()

在原始数据尾部添加另外数据组成新数据(字符串适用)。

//数组
const a = [1,2,3];
const b = [4,5];
const c = a.concat(b); // [1, 2, 3, 4, 5]

//字符串
const x = 'abc';
const y = 'def';
const z = x.concat(y); // abcdef

join()

以参数作为分隔符,将所有参数组成一个字符串返回(一般默认逗号隔开)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.join('-')); // 3-4-4-5-4-6-5-7

slice(start, end)

用于提取原来数组的一部分,会返回一个提取的新数组,原数组不变(字符串适用,不包括end)。

//数组
const arr = [3,4,4,5,4,6,5,7];
const a = arr.slice(25); // [4, 5, 4]

//字符串
const x = 'abcdefgh';
const y = x.slice(36); // def

splice()

用于删除原数组的一部分,并且可以在删除的位置添加新的数组成员,返回值是被删除的数组元素。(改变原数组) splice(t, v, s)t:被删除元素的起始位置;v:被删除元素个数;s:s以及后面的元素为被插入的新元素。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.splice(3212); // [5, 4]
console.log(arr); // [3, 4, 4, 12, 6, 5, 7]

map()

依次遍历数组成员,根据遍历结果返回一个新数组。(map方法同样适用于字符串,但是不能直接调用,需要通过函数的call方法,间接使用,或者先将字符串川转为数组,再使用)(不会改变原始数组)。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.map(item => item*2;) 
// [6, 8, 8, 10, 8, 12, 10, 14]

forEach()

跟map方法类似,遍历数组,区别是无返回值。

const arr =[3,4,4,5,4,6,5,7];
arr.forEach((item,index)=>{console.log(item)})

for in()

跟 map 方法类似,遍历对象或者数组。 但值得注意的是 for in 循环返回的值都是数据结构的 键值名 。遍历对象返回的对象的key值,遍历数组返回的数组的下标(key)。

// 对象
const obj = {a123b12c2 };
for (let a in obj) {console.log(a)} // a   b   c

//数组
const arr = [3,4,4,5];
for(let a in arr) {console.log(a)} // 0123

filter()

一个过滤方法,参数是一个函数,所有的数组成员依次执行该函数,返回结果为 true 的成员组成一个新数组返回。(不会改变原始数组)。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.filter(item => item % 3 > 1);
console.log(a); // [5, 5]

some()& every()

这两个方法类似于“断言”( assert ),用来判断数组成员是否符合某种条件。

const arr = [3,4,4,5,4,6,5,7];
arr.somefunction( item, index, array ){
  console.log'item=' + item + ',index='+index+',array='+array );return item > 3;
})

// item=3,index=0,array=3,4,4,5,4,6,5,7
// item=4,index=1,array=3,4,4,5,4,6,5,7

trueconsole.log( arr.everyfunction( item, index, array ){
  console.log'item=' + item + ',index='+index+',array='+array );return item > 3;
}));

// item=3,index=0,array=3,4,4,5,4,6,5,7
// false

some方法是只要有一个数组成员的返回值为true,则返回true,否则false;

every方法是需要每一个返回值为true,才能返回true,否则为false;

reduce()

依次处理数组的每个成员,最终累计成一个值。 格式:

reduce(a, b, x, y)

// a:必填,累计变量;
// b:必填,当前变量;
// x: 可选,当前位置;
// y:可选,原数组。
//简单用法
const arr = [3,4,4,5,4,6,5,7];
const a = arr.reduce((pre, cur) => {return pre+cur}) 

// 逗号写法
const a = arr.reduce((pre, cur) => (sum= pre+cur, sum))
console.log(a) // 38

//高级用法(举个数组去重和数组扁平化栗子)
const b = arr.reduce((pre, cur) => {if(!pre.includes(cur)) {return pre.concat(cur)} else {return pre }}, []) // [3, 4, 5, 6, 7]
const arrs = [[2,3,2], [3,4,5]]
const c = arr.reduce((pre, cur) => {return pre.concat(cur)}, []) // [2, 3, 2, 3, 4, 5]

reduce 的用法还有很多,剋各种尝试。

reduceRight()

与 reduce 方法使用方式相同,区别在于 reduceRight 方法从右到左执行(例子略过)。

indexOf()

返回给定元素在数组中的第一次出现的位置,如果没有则返回-1(同样适用于字符串)。

//数组
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.indexOf(4)) // 1
console.log(arr.indexOf('4'))  // -1

//字符串
conststring = 'asdfghj';
console.log(string.indexOf('a')) // 0

lastIndexOf()

返回给定元素在数组中最后一次出现的位置,没有返回-1(同样适用于字符串)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.lastIndexOf(4)) 
// 4(从左到右数最后出现的位置,字符串同理)

shuffle()

用洗牌算法随机打乱一个集合。

const arr = [1,2,3,4,5,6,7,8,9,10];
const shuffle = ([...arr]) => {  
  let m = arr.length; 
   while (m) {    
    const i = Math.floor(Math.random() * m--);    
    [arr[m], arr[i]] = [arr[i], arr[m]];  
  }  
  return arr;
};
console.log(shuffle(arr))
// [10, 9, 7, 5, 6, 4, 1, 2, 8, 3]

flatten()

简写为flat(),接收一个数组,无论这个数组里嵌套了多少个数组,flatten最后都会把其变成一个一维数组(扁平化)。

const arr = [[1,2,3],[4,5,[6,7]]];
const a = arr.flatten(3);
console.log(a); // [1234567]

Array.isArray()

用来判断是不是数据是不是一个数组,返回值为true或false。

const arr = [3,4,4,5,4,6,5,7];
console.log(Array.isArray(arr)) // true

copyWithin()

从数组的指定位置拷贝元素到数组的另一个指定位置中。

// 格式:
array.copyWithin(target, start, end)
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.copyWithin(4,2)) // [3, 4, 4, 5, 4, 5, 4, 6]

find()

返回符合传入测试(函数)条件的数组元素。

const arr = [3,4,4,5,4,6,5,7];
const a = test.find(item => item > 3);
console.log(a); // 4 
// (find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。)

const b = test.find(item => item == 0);
console.log(b); // undefined(如果没有符合条件的元素返回 undefined)

String

charAt()

用于返回指定位置的字符。

const str = 'hello guys';
console.log(str.charAt(3))  // l

charCodeAt()

用于返回指定位置的字符的Unicode编码。

const str = 'hello guys';
console.log(str.charCodeAt(3))  // 111

match()

用于在字符串内检索指定的值或找到一个或多个正则表达式的匹配,返回的是值而不是值的位置。

const str = 'hello guys';
console.log(str.match('guys'))  // ["guys"]

// 使用正则匹配字符串
const strs = '1.hello guys, 2.are you ok?';
console.log(strs.match(/\d+/g)) // ["1", "2"]

replace()

替换匹配的字符串。

const str = 'hello guys';
console.log(str.replace('guys', 'man'))  // hello man

search()

用于检索与字符串匹配的子串,返回的是地址,与 indexOf() 的区别是 search 是强制正则的,而 indexOf 只是按字符串匹配的。

const str = 'hello guys';
console.log(str.search('guys'))  // 6
console.log(str.indexOf('guys'))  // 6

// 区别
conststring = 'abcdefg.1234';
console.log(string.search(/\./)) // 7(转译之后可以匹配到 . 的位置)
console.log(string.indexOf(/\./)) // -1 (相当于匹配/\./,找不到则返回-1,只能匹配字符串)

split()

将字符串切割成数组。

const str = 'hello guys';
console.log(str.split('')) // ["h""e""l""l""o"" ""g""u""y""s"]
console.log(str.split(''3)) //  ["h""e""l"]

toLocaleLowerCase()& toLowerCase()

将字符串转换成小写。

const str = 'hello guys';
console.log(str.toLocaleLowerCase())  // hello 
guysconsole.log(str.toLowerCase())  //  hello guys

toLocaleUpperCase() & toUpperCase()

将字符串转换成大写。

const str = 'hello guys';
console.log(str.toLocaleUpperCase())  // HELLO GUYS
console.log(str.toUpperCase())  // HELLO GUYS

substr()

用于从起始索引号提取字符串中指定数目的字符。

const str = 'hello guys';
console.log(str.substr(2))  // llo guys
console.log(str.substr(27))  // llo guy

substring()

用于提取字符串中两个指定索引号之间的字符。(与 slice() 和 substr() 方法不同的是, substring() 不接受负的参数。)

const str = 'hello guys';
console.log(str.substring(2))   // llo guys
console.log(str.substring(27))  //  llo g

.trim()

去掉字符串两端的空格。

const str = '    hello guys    ';
console.log(str.trim()) // hello guys(不会改变原数组)

常用的http:// json.xxx 方法

JSON.parse()

用于把字符串转化为对象。

const str = '{"name""phoebe""age"20}';
const obj = JSON.parse(str)  
// {name: "phoebe", age: 20}(object类型)

JSON.stringify()

用于把对象转化为字符串。

const obj = {"name""Tins""age"22};
const str = JSON.stringify(obj)  
// {"name":"Tins","age":22}(string类型)

Object 实例对象的方法主要有以下六个

Object.Prototype.valueOf()

返回当前对象对应的值。( Object.valueOf() 相当于 Object.Prototype.ValueOf() 我们创建一个取代 valueOf() 方法的函数,但是需要注意的是方法必须不能传入参数 。假设我们有个对象叫 ObjectrType 而我想为它创建一个 valueOf() 方法。下面的代码为 valueOf() 方法赋予了一个自定义函数:

ObjectrType.prototype.valueOf = function() { 
  return customValue; 
};

有了这样的一个方法,下一次每当 ObjectrType 要被转换为原始类型值时, JavaScript 在此之前会自动调用自定义的 valueOf() 方法。valueOf() 方法一般都会被 JavaScript 自动调用,但我们也可以像下面代码那样自己调用:

ObjectrType.valueOf()

valueOf 同样适用于 string , number , symbol , boolean , date 。

Object.Prototype.toString()

返回当前对象对应的字符串形式。

functionDog(name) {
  this.name = name;
}
const dog1 = new Dog('Gabby');
Dog.prototype.toString = functiondogToString() {
  return'' + this.name;}
  console.log(dog1.toString()
);  // Gabby

Object.Prototype.toLocaleString()

返回当前对象对应的模块字符串。 语法:obj.toLocaleString();

let foo = {};
foo.toLocaleString(); // "[object Object]"

Object.Prototype.isPrototypeOf()

判断当前对象是否为另一个对象的原型。语法:

Object.prototype.isPrototypeOf(targetObj)
const arr = [];
Array.prototype.isPrototypeOf(arr); // true

// 修改obj的原型
Object.setPrototypeOf(arr, String.prototype);
Array.prototype.isPrototypeOf(arr); 
falseString.prototype.isPrototypeOf(arr); // true

Object.Prototype.hasOwnProperty()

判断某个属性是否为当前对象自身的属性,还是继承自原型对象的属性,并返回一个布尔值。 语法:Object.prototype.hasOwnProperty(prop)

let obj = {};
// 定义一个object实例
obj.prop1 = 'value1'// prop1是一个自有属性
obj.constructor.prototype.prop2 = 'value2'// prop2是一个原型链属性
// 无论自有属性还是原型链属性,我们都可以访问到console.info(obj.prop1); 
// value1
console.info(obj.prop2); // value2
// 使用`hasOwnProperty()`方法判断属性是否为自有属性
obj.hasOwnProperty('prop1'); 
trueobj.hasOwnProperty('prop2'); // false

Object.Prototype.PropertyIsEnumerable()

判断某个属性是否可枚举。 语法:Object.prototype.propertyIsEnumerable(prop)

const obj = { name'ecmaer'};
Object.getOwnPropertyDescriptor(obj, 'name').enumerable// true
obj.propertyIsEnumerable('name'); // true

// 将属性name设置成不可枚举
Object.defineProperty(obj, 'name', {enumerablefalse});
obj.propertyIsEnumerable('name'); 
falsefor(let i in obj){console.info(obj[i]); // 没有遍历出'ecmaer'}

Javascript的三种判断一个值的类型的办法

typeOf()

typeof 可用来检测数据类型: 需要注意的是 typeof 无法区分 null 、 Array 和 通常意义上的 object 。

typeof 123 //number
typeof '123' //string
typeof true // boolean
typeof false //boolean
typeof undefined // undefined
typeof Math.abs // function
typeof function () {} // function

// 当遇上`null`、`Array`和通常意义上的`object`,都会返回 object
typeof null // object

typeof [] // object(所以判断数组时可以使用Array.isArray(arr))

typeof {} // object

// 当数据使用了new关键字和包装对象以后,数据都会变成Object类型,不加new关键字时会被当作普通的函数处理。

typeof new Number(123); //'object'
typeof Number(123); // 'number'
typeof new Boolean(true); //'object'
typeof Boolean(true); // 'boolean'
typeof new String(123); // 'object'
typeof String(123); // 'string'

instanceOf()

instanceOf() 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链

function Car(make, model, year) {  
    this.make = make;  
    this.model = model;  
    this.year = year;
}
const auto = new Car('Honda''Accord'1998);
console.log(auto instanceof Car); // true
console.log(auto instanceof Object); // true

Object.Prototype.toString()(推荐)

可以精准的判断对象类型。 对于 array 、 null 、 object 来说,其关系错综复杂,使用 typeof 都会统一返回 object 字符串,要想区别对象、数组、函数单纯使用 typeof 是不行的,想要准确的判断对象类型,推荐使用 Object.Prototype.toString() ,它可以判断某个对象值属于哪种内置类型。

const arrs = [1,2,3];
console.log(typeof arrs) // object
console.log(Object.Prototype.toString.call(arrs))  // [object Array]

call,apply以及bind的用法,区别及相似住处

用法

call 直接调用该执行函数,在执行的时候,将函数内部的作用域绑定到指定的作用域。( call() 方法接受若干个参数的列表)

const arr = [2,5,4,7,6]
const a = Function.prototype.apply.call(Math.maxnull,arr)
console.log(a)  // 7

apply 直接调用该执行函数,在执行的时候,将函数内部的作用域绑定到指定的作用域。 call() 是 apply() 的一颗语法糖,作用和 apply() 一样,同样可实现继承,唯一的区别就在于 call() 接收的是参数列表,而 apply() 则接收参数数组。

const arr = [2,5,4,7,6]
const a = Function.prototype.call.apply(Math.max, arr)
console.log(a)  // 7

//如果apply的第二个参数是个null,会返回-Infinity
const b = Function.prototype.call.apply(Math.maxnull, arr)
console.log(b)  // -Infinity

bind 创建一个新的函数的引用,并绑定到一个作用域特定作用域上,同时支持传参。 bind 则和 call 的用法差不多,唯一区别是, call 和 apply 会立刻调用函数, bind 只是绑定 this 格式为:bind (作用域参数,参数1,参数2)

const fruits = {"name""apple"getOtherFriutfunction() {        return this.name;}}
const color = {"name"" is red"}
const fruitColor = fruits.getOtherFriut.bind(this, color)
console.log(fruitColor()) //is 

redconst arr = [2,5,4,7,6]
const a = Function.prototype.call.apply(Math.max, arr)
console.log(a)  // 7
//如果apply的第二个参数是个null,会返回-Infinity
const b = Function.prototype.call.apply(Math.maxnull, arr)
console.log(b)  // -Infinity

相似之处

  • 都是用来改变函数的this对象;

  • 第一个参数都是this要指向的对象;

  • 都可利用后继参数传参;

区别

  • 都可以用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

  • bind()是返回一个新函数,供以后调用,而apply()和call()是立即调用。

  • call()和apply()唯一区别是参数不一样,call()是apply()的语法糖;

选择使用

  • 如果不需要关心具体有多少参数被传入函数,选用apply();

  • 如果确定函数可接收多少个参数,并且想一目了然表达形参和实参的对应关系,用call();

  • 如果想要将来再调用方法,不需立即得到函数返回结果,则使用bind();

Date对象的用法

首先需要定义一个变量:

const date = new Date();

接下来就可以直接使用常见的Date对象方法。

Date(): 返回当日的日期和时间;

getDate(): 从Date对象返回一个月中的某一天(131)console.log(date.getDate());

getDay():从Date对象返回一周中的某一天(06);

getMonth(): 从Date对象返回月份(011);

getFullYear(): 从Date对象以四位数字返回年份;

getYear():可以使用getFullYear()代替;

getHours(): 返回Date()对象的小时(023);

getMinutes(): 返回Date()对象的分钟(059);

getSeconds(): 返回Date()对象的分钟(059);

getMillseconds(): 返回Date()对象的毫秒(0999);

getTime(): 返回197011日至今的时间;

getTimezoneOffset(): 返回本地时间与格林威治标准时间(GMT)的分钟差;

getUTCDate(): 根据世界时从Date对象返回月中的一天(131);

getUTCDay(): 根据世界时从Date对象返回周中的一天(16);

getUTCMonth(): 根据世界时从Date对象返回月份(011);

getUTCFullYear(): 根据世界时从Date对象返回四位数的年份;

getUTCHours(): 根据世界时从Date对象返回对象的小时(023);

getUTCMinutes(): 根据世界时从Date对象返回对象的分钟(059);

getUTCSeconds(): 根据世界时从Date对象返回对象的秒钟(059);

getUTCMillseconds(): 根据世界时从Date对象返回对象的毫秒(0999);

parse(): 返回197011日午夜到指定日期(字符串)的毫秒数;

setDate(): 设置Date对象中月的某一天(131);

setMonth(): 设置Date对象中月份(011);

setFullYear(): 设置Date对象中的年份(四位数字);

Math.xx开头的方法

Math.ceil(): 对数进行上舍入(天花板函数) 大于等于 x,并且与它最接近的整数。

Math.floor(): 对数进行下舍入(地板函数)。

Math.max(x,y):返回x,y中的最大值。

Math.min(x,y):返回x,y中的最小值。

Math.pow(x,y): 返回x的y次方。

Math.random() : 返回0-1之间的随机数。

Math.round(x): 四舍五入。

Math.abs(x):返回数的绝对值。

Math.acos(x):返回数的反余弦值。

Math.asin(x): 返回数的反正弦值。

Math.atan(x):返回数的反正切值。

Math.atan2(y,x):返回由x轴到点(x,y)的角度(以弧度为单位)。

Math.cos(x): 返回数的余弦值。

Math.exp(e): 返回e的指数。

Math.log(x):返回数的自然对数(以e为底数)。

Math.sin(x):返回数的正弦值。

Math.sqrt(x):返回数的平方根。

Math.tan(x): 返回角的正切值。

Math.toSource():返回该对象的源代码。

Math.valueOf(): 返回Math对象的原始值。

简单的数组去重

数组去重的几种方式在这里做一下归纳:

最便捷的方法:[…new Set(arr)]

const arr = [4,5,3,4,6,5,8,6];
console.log(Array.from(new Set(arr)))  // [4, 5, 3, 6, 8]
console.log([...new Set(arr)])  // [4, 5, 3, 6, 8]

recude+include去重

const arr = [4,5,3,4,6,5,8,6];
const a = arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]);
console.log(a) // [4, 5, 3, 6, 8]

利用filter去重

const arr = [4,5,3,4,6,5,8,6];
const b = arr.filter((item, index, arr) => arr.indexOf(item, 0) === index;)  // [4, 5, 3, 6, 8]

 

 
posted @   南柯Dream丶  阅读(235)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示