Math的一些
1、Math.abs(x)
含义: 返回 x 的绝对值
应用场景: 使 0.1+0.2 == 0.3
方法: 设置一个误差范围值,通常称为“机器精度”,而对于 Javascript 来说,这个值通常是2^-52,而在 ES6 中,已经为我们提供了这样一个属性:Number.EPSILON,而这个值正等于2^-52。这个值非常非常小,在底层计算机已经帮我们运算好,并且无限接近 0,但不等于 0,。这个时候我们只要判断(0.1+0.2)-0.3 小于 Number.EPSILON,在这个误差的范围内就可以判定 0.1+0.2===0.3 为true。
function numbersequal(a,b){
return Math.abs(a-b)<Number.EPSILON;
}
var a=0.1+0.2, b=0.3;
console.log(numbersequal(a,b)); //true
此时,需要考虑兼容性的问题,在 chrome 中支持这个属性,但是 IE 并不支持(笔者的版本是 IE10 不兼容),所以我们还要解决 IE 的不兼容问题。
Number.EPSILON = (function () {
//解决兼容性问题
return Number.EPSILON ? Number.EPSILON : Math.pow(2, -52);
})();
//上面是一个自调用函数,当JS文件刚加载到内存中,就会去判断并返回一个结果,相比if(!Number.EPSILON){
//Number.EPSILON=Math.pow(2,-52);
//}这种代码更节约性能,也更美观。
function numbersequal(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
//接下来再判断
var a = 0.1 + 0.2,
b = 0.3;
console.log(numbersequal(a, b)); //这里就为true了
2、Math.pow(x,y)
含义: 返回 x 的 y 次
应用场景: 上边的机器精度2^-52即可以用此方法求得
方法:
Math.pow(2, -52) = Number.EPSILON
3、Math.round()
含义: (小数点后第一位)大于五全部加,等于五正数加,小于五全不加。即四舍五入
应用场景:
// 小数点后第一位<5
正数:Math.round(11.46)=11
负数:Math.round(-11.46)=-11
// 小数点后第一位>5
正数:Math.round(11.68)=12
负数:Math.round(-11.68)=-12
// 小数点后第一位=5
正数:Math.round(11.5)=12
负数:Math.round(-11.5)=-11
4、Math.ceil()
含义: 天花板,向上取整
应用场景:
Math.ceil(11.46)=Math.ceil(11.68)=Math.ceil(11.5)=12
Math.ceil(-11.46)=Math.ceil(-11.68)=Math.ceil(-11.5)=-11
5、Math.floor()
含义: 地板,向下取整
应用场景:
Math.floor(11.46)=Math.floor(11.68)=Math.floor(11.5)=11
Math.floor(-11.46)=Math.floor(-11.68)=Math.floor(-11.5)=-12
1、ES5数组方法
1、push()
含义: 接受多个参数,并将这些参数放置于数组尾部,返回新数组的长度,原始数组发生改变。
应用场景:
let arr=[1,2,3];
arr.push(4,5,6);
console.log(arr.push(4,5,6))//6
console.log(arr);//[1,2,3,4,5,6];
2、pop()
含义: 不接收参数,从数组尾部删除一个元素,并返回这个删除的元素,原数组发生改变。
应用场景:
var arr = [1,2,3,4]
console.log(arr.Pop( ))//4
console.log(arr);//[1,2,3]
3、unshift()
含义: 接受多个参数并将这些参数放置于数组头部,返回新数组的长度,原数组发生改变。
应用场景:
var arr=[1,2,5,3];
arr.unshift(10,11)//6
console.log(arr)//[10,11,1,2,5,3];
4、shift()
含义: 不接受参数,从数组的头部删除一个元素,并返回这个删除的元素,原数组发生改变。
应用场景:
var arr = [1,2,3,4]
arr.myShift()//1
console.log(arr)//[2,3,4]
5、slice()
含义: 如果是一个参数,那么该参数表示的索引开始截取,直至数组结束,返回截取的数组,原数组不发生改变。
如果有两个参数,从第一个参数表示的索引开始截取,到第二个参数表示的索引结束,不包括第二个参数对应的索引位上的元素。
应用场景:
var arr=[1,2,3,4,5,6]
var arr1=arr.slice(1,3)//[ 2, 3 ]
var arr1=arr.slice()//[ 1, 2, 3, 4, 5, 6 ]
//如果没有任何参数就会从头截取到尾部 拷贝
var arr1=arr.slice(1)//[ 2, 3, 4, 5, 6 ]
//如果第二个参数没有,就会从开始截取到尾部
var arr1=arr.slice(-3,-1)//[ 4, 5 ]
//如果是负数就会从后向前数,然后再截取
//前小于后将参数转换为正向数值时,前面的必须小于后面
var arr1=arr.slice(-3,5)//[ 4, 5 ]
//如果第一个参数大于等于数组长度,或者第二个参数小于第一个参数,则返回空数组。
console.log(arr1,arr)//[ 4, 5 ] [ 1, 2, 3, 4, 5, 6 ]
注: slice方法的一个重要应用,是将类似数组的对象转为真正的数组。
Array.prototype.slice.call({ 0:'a', 1:'b', length:2 }) //[ 'a', 'b' ]
Array.prototype.slice.call(document.querySelectorAll("div"));
Array.prototype.slice.call(arguments);
上面代码的参数都不是数组,但是通过call方法,再它们上面调用slice方法,就可以把它们转为真正的数组。
6、splice()
含义: 如果一个参数,那么从该参数表示的索引开始截取,直至数组结束,返回截取的数组,原数组发生改变。
如果有两个参数,从第一个参数表示索引,第二个参数表示的是截取的长度。
如果有三个及以上参数,从第一个参数表示索引,第二个参数表示的是截取的长度,后边的会从截取的位置添加至原数组里。
应用场景:
var arr = ['a', 'b', 'c', 'd', 'e', 'f']
//从原数组4号位置,删除了两个数组成员
arr.splice(4,2) //["e", "f"]
//原数组发生改变
console.log(arr) //["a", "b", "c", "d"]
//删除了两个,又插入了两个新元素
arr.splice(4,2,1,2) //["a", "b", "c", "d", 1, 2]
//如果起始位置使复数,就表示从倒数位置开始(不包括该元素)删除
//从倒数第四个位置c开始删除两个元素
arr.splice(-4,2)//["c", "d"]
//添加元素;如果只是单纯地插入元素,splice方法的第二个参数可以设为0。
var arr = [1, 1, 1]
arr.splice(1, 0, 2) // [ ]
console.log(arr) // [ 1, 2, 1, 1 ]
//如果只提供第一个参数,等同于将原数组在指定位置拆分成两个数组。
var a = [1, 2, 3, 4]
arr.splice(2) //[3, 4]
console.log(arr) //[1, 2]
7、reverse()
含义: 数组翻转参数无意义;改变数组;并返回操作后的原数组。
应用场景:
var arr=[1,2,4,5,6,7,7,4,3,5]
arr.reverse( )
console.log(arr)//[5, 3, 4, 7, 7, 6, 5, 4, 2, 1]
8、sort()
含义: 对数组的元素做原地的排序,并返回这个数组。sort可能不稳定,默认按照字符串的unicode码位点排序。改变数组;并返回操作后的原数组。
应用场景:
var arr = [2, 11, 50, 7, 9];
//按照字符串按位比较方式来判断大小的,不稳定
console.log(arr.sort()); //[ 11, 2, 50, 7, 9 ]
//增加判断条件
arr.sort(function (a, b) {
return a - b; //从小到大 [ 2, 7, 9, 11, 50 ]
return b - a; //从大到小 [ 50, 11, 9, 7, 2 ]
})
console.log(arr);
[10111, 1101, 111].sort(function (a, b) {return a - b;})//[ 111, 1101, 10111 ]
[4, 3, 2, 1].sort() // [1, 2, 3, 4]
[11, 101].sort() // [101, 11]
[
{ name:"张三", age:30 },
{ name:"李四", age:24 },
{ name:"王五", age:28 }
]
.sort(function (o1, o2) {
return o1.age - o2.age;})
// [
// { name: '李四', age: 24 },
// { name: '王五', age: 28 },
// { name: '张三', age: 30 }
// ]
9、join()
含义: 将数组中元素以参数来进行拼接;不改变原数组
应用场景:
var arr = [1,2,3,4];
var str = arr.join("-----");
console.log(str,arr)
//1-----2-----3-----4 [ 1, 2, 3, 4 ]
10、concat()
含义: 合并数组,将参数放到原数组里,如果参数是一个数组,把数组中的元素提出来,放到原数组后边。不改变原数组,参数为元素也可以。
应用场景:
var arr1 = [1, 2, 3],
arr2 = ['a', 'b', 'c'];
console.log("arr1.concat(arr2):", arr1.concat(arr2));
console.log("arr1:", arr1);
console.log("arr2:", arr2);
console.log("arr2.concat(arr1):", arr2.concat(arr1));
// arr1.concat(arr2): [ 1, 2, 3, 'a', 'b', 'c' ]
// arr1: [ 1, 2, 3 ]
// arr2: [ 'a', 'b', 'c' ]
// arr2.concat(arr1): [ 'a', 'b', 'c', 1, 2, 3 ]
11、toString()
含义: 使数组变成字符串,用’,’连接。若数组的值存在数组,会便遍历拼接在字符串里;对象,会变成[object Object];undefined则什么都不连接,返回最后转化的字符串;不会改变原数组。
应用场景:
var a=1234567
console.log(a.toString())//1,234,567
var arr = [1,2,3]
console.log(arr.toString())//1,2,3
var a=new Date()
console.log(a)//2021-03-14T08:13:00.225Z
console.log(a.toString())//Sun Mar 14 2021 16:12:16 GMT+0800 (中国标准时间)
12、toLocaleString()
含义: 使数组变成字符串,用’,’连接。数组内的元素会调用自己的toLocalString方法;返回最后转化的字符串;不会改变原数组。
应用场景:
var a=1234567//当数字是四位及以上时,toLocaleString()会让数字三位三位一分隔,有符号和小数点也无所谓
console.log(a.toLocaleString())//1,234,567
var arr = [1,2,3]//对于数组,这两种方法没有区别
console.log(arr.toLocaleString())//1,2,3
var a=new Date()
console.log(a.toLocaleString())//2021/3/14 下午4:13:00
toString()方法与toLocalString()方法区别:
toLocalString()是调用每个数组元素的 toLocaleString() 方法,然后使用地区特定的分隔符把生成的字符串连接起来,形成一个字符串。
toString()方法获取的是String(传统字符串),而toLocaleString()方法获取的是LocaleString(本地环境字符串)。
如果你开发的脚本在世界范围都有人使用,那么将对象转换成字符串时请使用toString()方法来完成。
LocaleString()会根据你机器的本地环境来返回字符串,它和toString()返回的值在不同的本地环境下使用的符号会有微妙的变化。
所以使用toString()是保险的,返回唯一值的方法,它不会因为本地环境的改变而发生变化。如果是为了返回时间类型的数据,推荐使用LocaleString()。若是在后台处理字符串,请务必使用toString()。
13、for()
含义: 遍历数组
应用场景:
var arr = ["a", "b", "c", "d", ["a", "b", "c", "d"]];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//a
//b
//c
//d
//[ 'a', 'b', 'c', 'd' ]
//二维数组
var arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (var i = 0; i < arr.length; i++) { //遍历数组
for (var j = 0; j < arr[i].length; j++) { //遍历子数组所有数据
console.log(arr[i][j]);
}
}
//1 2 3 4 5 6 7 8 9(竖着排,一个个)
14、for in
含义: 循环遍历数据
应用场景:
for…in循环遍历的是数组的索引,再通过索引值获取数组值
var arr = ['a','b','c'];
for (const key in arr) {
console.log(key); // 0,1,2
console.log(arr[key]); // a b c
}
当遍历自定义对象时,for…of会报错,明显for…in最佳
// for...in循环遍历的是对象的键值,再通过键值获取对应的值
var obj = {id:1,name:'d',age:30}
for (const key in obj) {
console.log(key,obj[key]);
}
2、ES6新增数组方法
1、for of
含义: 与for in一样,都是循环遍历数据的
应用场景:
for…of循环遍历的是数组的值,遍历数组时,for of最佳
for (const item of arr) {
console.log(item); // a b c
}
//for...of报错
for (const item of obj) {
console.log(item);
}
2、indexOf()
含义: 找出数组中是否有给定值的元素,并返回找到的第一个元素的索引值;如果没有则返回-1。
应用场景:
// 原理:indexOf方法,在数组循环过程中会和传入的参数比对,
// 如果是比对成功,那么终止循环,返回对比成功的下标。
var arr = ["a", "b", "c", "d", "b"];
var b=arr.indexOf("b");
console.log(arr)//[ 'a', 'b', 'c', 'd', 'b' ]
console.log(b)//1
3、lastIndexOf ()
含义: 找出数组中是否有给定值的元素,并返回找到的最后一个元素的索引值;如果没有则返回-1。
应用场景:
同时使用indexOf()和lastIndexOf ()可以实现对数组的去重。
具体方法:如果查询相同的参数,但下标不同,则删除掉该元素(splice())
var arr = ["a", "b", "c", "d", "b"];
var b=arr.lastIndexOf("b");
console.log(arr)//[ 'a', 'b', 'c', 'd', 'b' ]
console.log(b)//4
4、forEach()
含义: 如果不接受参数,遍历数组中每一个元素。
如果接受参数,分别为:item, index, array, (用不到时可以不写);item 表示每次迭代的元素;index 表示每次迭代元素的下标;array 表示原数组。
应用场景:
var a = [1,2,3];
a.forEach(function(value,key,arr){
console.log(value)
// 结果依次为1,2,3
console.log(key)
// 结果依次为0,1,2
console.log(arr)
// 三次结果都为[1,2,3],该参数貌似没什么用
})
也可以用来实现累加
var arr = [1, 2, 3, 4];
var sum = 0;
arr.forEach(function (value, index, array) {
array[index] == value; //结果为true
sum += value;
});
console.log(sum); //结果为 10
5、.map() .filter() .reduce() 结合使用
5、map()
含义: 返回一个新数组,新数组是原数组的映射;不改变原数组的值;新数组的元素值是每次函数return的返回值;若不写return,接收的新数组的元素值将全为空。
应用场景:
var arr = [20,13,11,8,0,11];
var brr = arr.map(function(item){
//将数组的每个元素都将增加到原来的1.2倍
return item*1.2;//[ 24, 15.6, 13.2, 9.6, 0, 13.2 ]
// 此时brr为a数组每个元素的1.2倍
return 1//[ 1, 1, 1, 1, 1, 1 ]
//若return 1,则新数组的每个元素值均为1
})
console.log(brr);
var arr = [20,13,11,8,0,11];
const map1 = arr.map(x => x *2);
console.log(map1);//[ 40, 26, 22, 16, 0, 22 ]
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);//开平方
console.log("roots is : " + roots );//roots is : 1,2,3
附一个.map() .filter() .reduce() 的用法-----这里我们只讲述map()的用法,filter()在第6点,reduce()在第7点
如果说你收到一组包含多个对象的数组,每个对象是一个 person。最终你只希望得到一个只包含 id 的数组。我想你有多种方式来实现这个目标:.forEach() , .for(…of) ,或者 一个简单的 .for()
// What you have
var officers = [
{ id: 20, name: 'Captain Piett' },
{ id: 24, name: 'General Veers' },
{ id: 56, name: 'Admiral Ozzel' },
{ id: 88, name: 'Commander Jerjerrod' }
];
// What you need
[20, 24, 56, 88]
让我们来看看.map()是如何做到的。
var officersIds = officers.map(function (officer) {
return officer.id
});
我们可以使用箭头函数做到更加的精简。
const officersIds = officers.map(officer => officer.id);
那么 .map() 是怎么运行的呢?实际上对数组的每个元素都遍历一次,同时返回一个新的值。记住一点是返回的这个数据的长度和原始数组长度是一致的。
6、filter()
含义: 过滤元素,返回一个新数组;新的数组由每次函数返回值为true对应的元素组成;原数组不受影响。
应用场景:
将数组中的奇数取出来,放入到一个新数组中
var arr = [20,13,11,8,0,11];
var brr =arr.filter(function(item){
//返回值为奇数的元素
return item%2;
})
console.log(brr);//[ 13, 11, 11 ]
如果你有一个数组,你只想要这个数组中的一些元素怎么办呢?这时候 .filter() 就非常好用了。
var pilots = [{
id: 2,
name: "Wedge Antilles",
faction: "Rebels",
},
{
id: 8,
name: "Ciena Ree",
faction: "Empire",
},
{
id: 40,
name: "Iden Versio",
faction: "Empire",
},
{
id: 66,
name: "Thane Kyrell",
faction: "Rebels",
}
];
如果我们现在想要两个数组:一个是 rebel 飞行员,一个是 imperials 飞行员,用 .filter() 将会非常简单~
var rebels = pilots.filter(function (pilot) {
return pilot.faction === "Rebels";
});
var empire = pilots.filter(function (pilot) {
return pilot.faction === "Empire";
});
我们还可以用箭头函数更优雅的表达:
const rebels = pilots.filter(pilot => pilot.faction === "Rebels");
const empire = pilots.filter(pilot => pilot.faction === "Empire");
总结:如果 callback 函数返回 true,这个元素将会出现在返回的数组中,如果返回 false 就不会出现在返回数组中。
7、reduce()
含义: 返回值是最后一次函数调用的返回值;
不写return时,默认返回undefined;
运行机制:一开始,prev代表数组第一个元素,next指向数组第二个元素 ;函数有个返回值,会作为下次的prev值;当给方法第二个参数值时,prev从传的第二个参数值开始,next从第一个元素值开始。
应用场景:
一个简单的例子,你就能感受到 .reduce() 的用法了。假如你有一个包含一些飞行员以及他们飞行经验的数组。
var pilots = [{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 16,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];
如果你需要知道所有飞行员的总飞行年数。用 .reduce() 将会非常直观。
var totalYears = pilots.reduce(function (accumulator, pilot) {
return accumulator + pilot.years;
}, 0);
console.log(totalYears)//82
可以看到我们开始先用0初始化了我们的 accumulator 的值,如果需要我们可以用其他的值去初始化 accumulator 。 在对每个元素运行 callback 函数之后,reduce 将会返回最终值给我们(例子中:82)
同样我们可以用箭头函数精简我们的代码:
const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);
假如我们需要知道飞行员中飞行年限最长的那位,我们可以这样获取:
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});
console.log(mostExpPilot)//{ id: 2, name: "Temmin 'Snap' Wexley", years: 30 }
总结:reduce 可以直观的返回数组里面指定的一个值或者对象
附一个 .map() .filter() .reduce() 的结合使用
因为 .map() 和 .filter()都返回一个数组,所以我们可以轻松的用链式编程的方法来综合使用它们。
假设我们有如下数据:
var personnel = [{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];
我们的目标是:获取属性为 force 的用户总值,读者可以先自行思考一下,用于巩固前面所学知识,我们可以如下处理。
var totalJediScore = personnel
.filter(function (person) {
return person.isForceUser;
})
.map(function (jedi) {
return jedi.pilotingScore + jedi.shootingScore;
})
.reduce(function (acc, score) {
return acc + score;
}, 0);
console.log(totalJediScore)//420
同样,我们也可以用箭头表达式精简他们。
const totalJediScore = personnel
.filter(person => person.isForceUser)
.map(jedi => jedi.pilotingScore + jedi.shootingScore)
.reduce((acc, score) => acc + score, 0);
console.log(totalJediScore)//420
8、reduceRight()
含义: 该方法接收一个函数作为累加器(accumulator),数组中的每个值(从右到左)开始合并,最终为一个值;与reduce原理类似;不会改变原数组并迭代到最后的返回值
应用场景:
var arr = [1,4,5,7,8,10];
var res = arr.reduceRight(function(prev,next){
console.log(prev+"---"+next);
return prev+next;
},0) //prev从传的第二个参数值0开始,next从第一个元素值开始
console.log(res);
//0---10
//10---8
//18---7
//25---5
//30---4
//34---1
//35
9、some()
含义: return返回的值只要有一项为true,最终的返回值就为true,不会继续遍历后边的元素;
若没有一项满足返回值为true的,就返回false;原数组不受影响;
应用场景:
var arr = [20,13,11,8,0,11];
var brr = arr.some(function(item){
return item>10;
})
console.log(brr) //true
10、every()
含义: 对数组的每一项执行给定的函数,假如该函数每一项都返回true,最后结果才为true;
只要有一项返回值为false,最后结果就是false。且后边的元素都不会再继续执行函数;
原数组不受影响;
应用场景:
var arr = [20,13,11,8,0,11];
var brr = arr.every(function(item){
return item<100;
})
console.log(brr) //true
3、ES7新增数组方法
1、keys()
含义: 返回一个新的Array迭代器,它包含数组中每个索引的键;不会改变数组。
应用场景:
let arr=[1,2,234,'sdf',-2];
for(let a of arr.keys( )){
console.log(a)
}
//结果:0,1,2,3,4
//此处keys,对数组索引进行遍历
2、values()
含义: 返回一个新的Array迭代器,它包含数组中每个值的键;该方法不会改变数组。
应用场景:
let arr=[1,2,234,'sdf',-2];
for(let a of arr.values()){
console.log(a) }
//结果:1,2,234,sdf,-2
//values, 遍历了数组arr的值
3、entries()
含义: 返回一个新的Array迭代器,它包含数组中每个键值对[index,item];该方法不会改变数组。
应用场景:
let arr=[1,2,234,'sdf',-2];
for(let a of arr.entries()){
console.log(a)
}
// [ 0, 1 ]
// [ 1, 2 ]
// [ 2, 234 ]
// [ 3, 'sdf' ]
// [ 4, -2 ]
4、includes()
含义: includes函数与string的includes一样,接收2个参数,查询的项以及查询起始位置。用来判断当前数组是否包含某指定的值;返回一个布尔值;该方法不会改变数组。
应用场景:
let arr=[1,2,234,'sdf',-2];
console.log(arr.includes(2));//true
console.log(arr.includes(2,1));//true
console.log(arr.includes(20));//false
5、Array.from()
含义: 在一个类似数组或可迭代对象中创建一个新的数组实例并返回该数组实例。
应用场景:
返回数组的长度取决于对象中的length,故此项必须有!
console.log(Array.from({
'0': 'w',
'1': 'b',
length: 2
}))//[ 'w', 'b' ]
数组后2项没有属性去赋值,故undefined
console.log(Array.from({
'0': 'w',
'1': 'b',
length: 4
}))//[ 'w', 'b', undefined, undefined ]
length小于key的数目,按序添加数组
console.log(Array.from({
'0': 'w',
'1': 'b',
length: 1
}))//[ 'w' ]
返回p元素数组
let ps=document.getElementsByTagName('p');
Array.from(ps)
遍历字符串,返回一个数组
let b=Array.from('wbiokr')//[ 'w', 'b', 'i', 'o', 'k', 'r' ]
console.log(b);
第二个参数为回调函数
let b = Array.from([1, 2, 3], function (x) {
return x + 1
})
console.log(b);//[ 2, 3, 4 ]
6、Array.isArray( )
含义: 用于判断一个元素是否为数组返回布尔值还可以用于创建一个具有可变数量参数的新数组实例;并返回该数组实例。
应用场景:
let b = Array.isArray({
a: [1, 2, 3]
})
console.log(b);//false
7、fill()
含义: 将数组中指定区间的所有元素的值,都替换成第一个参数值;当第三个参数大于数组长度时候,以最后一位为结束位置。该方法会改变数组;没有返回值。
应用场景:
let arr=['w','b'];
arr.fill('i')//结果:['i','i'],改变原数组
第二个参数表示填充起始位置
arr.fill('o',1)
//结果:['i','o']改变原数组
第三个数组表示填充的结束位置
new Array(3).fill('k').fill('r',1,2)
//结果:['k','r','k']
8、copyWithin()
含义: 用于在数组内的替换操作,即替换元素和被替换元素都是数组内的元素;copyWithin方法接收三个参数,被替换数据的开始处、替换块的开始处、替换块的结束处(不包括);copyWithin(s,m,n)。该方法会改变数组,并返回改变后的数组。
应用场景:
此时数组不变
console.log(["a", "b", "c"].copyWithin(0))//[ 'a', 'b', 'c' ]
数组从位置2开始被原数组覆盖,只有2之前的0、1项保持不变
console.log(["a", "b", "c","d","e","f"].copyWithin(2));//[ 'a', 'b', 'a', 'b', 'c', 'd' ]
console.log(["a", "b", "c","d","e","f"].copyWithin(3));//[ 'a', 'b', 'c', 'a', 'b', 'c' ]
数组从第一项a之后开始被替换,被填充的数据是从原数组的第二项c开始到结束f;数量不够时,终止,不影响原始的数据
console.log(["a", "b", "c","d","e","f"].copyWithin(1,2))//[ 'a', 'c', 'd', 'e', 'f', 'f' ]
数组从第一项a之后开始被替换,被填充的数据是从原数组的第二项c开始,到第四项d(不包括第四项)结束。
console.log(["a", "b", "c","d","e","f"].copyWithin(1,2,4))//[ 'a', 'c', 'd', 'd', 'e', 'f' ]
9、find( )
含义: 返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。该方法不改变原数组。
应用场景:
let arr=[1,2,234,'sdf',-2];
arr.find(function(x){
return x<=2;
})//结果:1,返回第一个符合条件的x值
let arr = [1, 2, 234, 'sdf', -2];
let b = arr.find((x, i) => {
if (x < 2) {
console.log(x, i)
}
})// 1 0
// -2 4
10、findIndex( )
含义: 返回数组中满足提供的测试函数的第一个元素的值的索引。否则返回 undefined。该方法不改变原数组。findIndex和find差不多,不过默认返回的是索引。
应用场景:
let arr = [1, 2, 234, 'sdf', -2];
let b = arr.findIndex((x) => {
return x <= 2;
})
console.log(b)//0,返回第一个符合条件的x值的索引
let arr = [1, 2, 234, 'sdf', -2];
arr.findIndex((x, i) => {
if (x < 2) {
console.log(x, i)
}
})// 1 0
// -2 4

这篇博客详细介绍了JavaScript中的数组方法,包括ES5的Math函数和数组方法,如Math.abs()、push()、filter()等,以及ES6和ES7的新特性,如for of、includes()、find()等。通过实例展示了如何使用这些方法,并讨论了它们在不同场景下的应用。
354

被折叠的 条评论
为什么被折叠?



