1、数组的一些方法的注意点
reduce:
- 用法:arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])
accumulator 累计器
——累加器累加回调函数的返回值。currentValue 当前值
——处理数组的当前元素。currentIndex 当前索引
(可选)array 数组
(可选)- 案例:
// 对数组的所有值求和
const numbersArr = [67, 90, 100, 37, 60];
const total = numbersArr.reduce(function(accumulator, currentValue){
console.log("accumulator is " + accumulator + " current value is "+currentValue);
return accumulator + currentValue;
}, 0);
//accumulator is 0 current value is 67
//accumulator is 67 current value is 90
//accumulator is 157 current value is 100
//accumulator is 257 current value is 37
//accumulator is 294 current value is 60
//total : 354
console.log(total); // 354
// 数组扁平化
const twoDArr = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ];
const oneDArr = twoDArr.reduce(
(accumulator, currentValue) => accumulator.concat(currentValue),
[]
);
console.log(oneDArr);// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
// 数组最大值
const a = [23,123,342,12];
const max = a.reduce(
(accumulator,cur,inde,arr)=>{
return accumulator>cur?accumulator:cur;
},0
); // 342
// 求字符串中字母出现的次数
const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';
const res = str.split('').reduce(
(accumulator, cur) => {
accumulator[cur] ? accumulator[cur]++ : accumulator[cur] = 1;
return accumulator;
}, {}
);
// 数组 转对象
const streams = [{name: '技术', id: 1}, {name: '设计', id: 2}];
const obj = streams.reduce(
(accumulator, cur) => {accumulator[cur.id] = cur; return accumulator;},
{}
);
// 对象数组去重
const hash = {};
chatlists = chatlists.reduce((obj, next: Object) => {
const hashId = ${next.id}`;
if (!hash[hashId]) {
hash[`${next.id}`] = true;
obj.push(next);
}
return obj;
}, []);
slice:
- 用法:array.slice(start,end) 或者 string.slice(start,end)
- 案例:
//如果不传入参数二,那么将从参数一的索引位置开始截取,一直到数组尾
let a=[1,2,3,4,5,6];
let b=a.slice(0,3); //[1,2,3]
let c=a.slice(3); //[4,5,6]
splice:
- 用法:array.splice(start,deleteCount,item...)
- 案例:
//splice方法从array中移除一个或多个数组,并用新的item替换它们。
//参数start是从数组array中移除元素的开始位置。参数deleteCount是要移除的元素的个数。
let a=['a','b','c'];
let b=a.splice(1,1,'e','f'); //a=['a','e','f','c'],b=['b']
split
- 用法:string.split(separator,limit)
- 案例:
//split方法把这个string分割成片段来创建一个字符串数组。
//可选参数limit可以限制被分割的片段数量。separator参数可以是一个字符串或一个正则表达式。
//separator是一个空字符,会返回一个单字符的数组
let a="0123456";
let b=a.split("",3); //b=["0","1","2"]
substring 类似 slice, 但是substring不接受负数
- 用法:string.slice(start,end)
- 案例:
//如果不传入参数二,那么将从参数一的索引位置开始截取,一直到数组尾
let a='123456';
let b=a.substring(0,3); //[1,2,3]
let c=a.substring(3); //[4,5,6]
substr
- 用法:string.substr(start,length)
- 案例:
let a='123456';
let b=a.substr(0,3); //[1,2,3]
shift unshift
- 用法:array.shift()移除数组中第一项并返回该项
- array.unshift()从数组的前端添加项
- 案例:
const colors = ["black", "red", "green"]
let item=colors.shift()
console.log(item)// black
console.log(colors)// red green
push pop
- 用法:array.push()从数组的后端添加项
- array.pop()从数组末端移除项
- 案例:
const colors = ["black", "red", "green"]
let item=colors.pop()
console.log(item)// black
console.log(colors)// black red
2、 使用javascript 进行进制转换
将任意进制转换成十进制
parseInt("11", 2); // 3 2进制转10进制
parseInt("77", 8); // 63 8进制转10进制
parseInt("af", 16); //175 16进制转10进制
将10进制转换为2进制,八进制,十六进制字符串
(152).toString(2) // "10011000" ; 先用括号将152转换“包”成一个对象, 或者如下写法;
152..toString(2) // 这里第一个点将152转换成float类型的小数,第二个点是引出对象方法;
152..toString(16) // "98" : 十进制转16进制
152..toString(32) // "4o" :十提制转32进制
3、JS流程控制语句
- 退出循环break 在while、for、do...while、while循环中使用break语句退出当前循环,直接执行后面的代码。
4、向上取整、向下取整、四舍五入等
向下取整(<= 该数值的最大整数,和parseInt()一样)
Math.floor(5.1234); // 5
向上取整(有小数,整数部分就+1)
Math.ceil(5.1234);// 6
四舍五入(小数部分)
Math.round(5.1234); // 5
Math.round(5.6789); // 6
返回两数中的较大者
Math.max(1,2); // 2
随机数(0-1)
Math.random();
指定范围的随机数(m-n之间)的公式 Math.random()*(n-m)+m
document.write(Math.random()*(20-10)+10);//返回10-20的随机数
打乱数组
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
return Math.random() - 0.5;
});
// 输出(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again (9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
5、for-in 和 for-of 的区别
-
for-in总是得到对象的key或数组、字符串的下标。
-
for-of总是得到对象的value或数组、字符串的值,另外还可以用于遍历Map和Set
6、对字符串、数字或对象数组进行排序
sort()
和reverse()
// 排序字符串数组
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出 ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// 输出 ["Steve", "Musk", "Kapil", "Joe"]
// 排序数字数组
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出 [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// 输出 [100, 40, 25, 10, 5, 1]
- 对象数组排序
localeCompare
方法用于比较两个字符串,它返回一个整数,该方法的最大特点,就是会考虑自然语言的顺序,localCompare是根据我们的中文系统,把汉字先转换成了拼音,再进行了比较;对于同拼音的汉字,js再根据声调进行比较
// 如果等于-1,表示第一个字符串小于第二个字符串;
'apple'.localeCompare('banana') // -1
// 如果等于0,表示两者相等
'apple'.localeCompare('apple') // 0
const objectArr = [ { first_name: 'Lazslo', last_name: 'Jamf' },{ first_name: 'Pig', last_name: 'Bodine' },{ first_name: 'Pirate', last_name: 'Prentice' } ];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出 length: 3 [{…}, {…}, {…}]
// 0: {first_name: "Pig", last_name: "Bodine"}
// 1: {first_name: "Lazslo", last_name: "Jamf"}
// 2: {first_name: "Pirate", last_name: "Prentice"}