- 声明和初始化数组
const array = Array(5).fill('');
// 输出
(5) ["", "", "", "", ""]
//或者
const matrix = Array(5).fill(0).map(() => Array(5).fill(0))
// 输出
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5
//或者
const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))
> Result:(4) [1, 2, 3, 5]
- 求和,最小值和最大值
const array = [5,4,7,8,9,2];
//求和
array.reduce((a,b) => a+b);// 输出: 35
//最大值
array.reduce((a,b) => a>b?a:b);// 输出: 9
//最小值
array.reduce((a,b) => a<b?a:b);// 输出: 2
3.排序字符串,数字或对象等数组
//字符串数组排序
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出
(4) ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// 输出
(4) ["Steve", "Musk", "Kapil", "Joe"]
//数字数组排序
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出
(6) [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// 输出
(6) [100, 40, 25, 10, 5, 1]
//对象数组排序
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));
// 输出
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
4.从数组中过滤到虚值
const array = [3, 0, 6, 7, '', false, undefined, null];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]
- 去除重复值
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]
- 创建一个计数器对象或 Map
let string = 'kapilalipak';
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}
//或者
const countMap = new Map();
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {
countMap.set(string[i], 1);
}
}
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
7.将十进制转换为二进制或十六进制
const num = 10;
num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"
8.数组截断
如果你想从数组末尾删除值(删除数组中的最后一项),有比使用splice()更快的替代方法。
例如,你知道原始数组的大小,可以重新定义数组的length属性的值,就可以实现从数组末尾删除值:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array.length)
> Result: 10
array.length = 4
console.log(array)
> Result: (4) [0, 1, 2, 3]
这是一个特别简洁的解决方案。但是,slice()方法运行更快,性能更好:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array);
> Result: [0, 1, 2, 3]
9.获取数组的最后一项
数组的slice()取值为正值时,从数组的开始处截取数组的项,如果取值为负整数时,可以从数组末属开始获取数组项。
let array = [1, 2, 3, 4, 5, 6, 7]
const firstArrayVal = array.slice(0, 1)
> Result: [1]
const lastArrayVal = array.slice(-1)
> Result: [7]
console.log(array.slice(1))
> Result: (6) [2, 3, 4, 5, 6, 7]
console.log(array.slice(array.length))
> Result: []
正如上面示例所示,使用array.slice(-1)获取数组的最后一项,除此之外还可以使用下面的方式来获取数组的最后一项:
console.log(array.slice(array.length - 1))
> Result: [7]
10.拍平多维数组
const arr = [1, [2, '大漠'], 3, ['blog', '1', 2, 3]]
const flatArray = [].concat(...arr)
console.log(flatArray)
> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]
不过上面的方法只适用于二维数组。不过通过递归调用,可以使用它适用于二维以下的数组:
function flattenArray(arr) {
const flattened = [].concat(...arr);
return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened;
}
const array = [1, [2, '大漠'], 3, [['blog', '1'], 2, 3]]
const flatArr = flattenArray(array)
console.log(flatArr)
> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]
11.动态更改对象的key
在过去,我们首先必须声明一个对象,然后在需要动态属性名的情况下分配一个属性。在以前,这是不可能以声明的方式实现的。不过在ES6中,我们可以实现:
const dynamicKey = 'email'
let obj = {
name: '大漠',
blog: 'w3cplus',
[dynamicKey]: 'w3cplus@hotmail.com'
}
console.log(obj)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}
12.数据类型转换
JavaScript中数据类型有Number、String、Boolean、Object、Array和Function等,在实际使用时会碰到数据类型的转换。在转换数据类型时也有一些小技巧
转换为布尔值
布尔值除了true和false之外,JavaScript还可以将所有其他值视为“真实的”或“虚假的”。除非另有定义,JavaScript中除了0、’’、null、undefined、NaN和false之外的值都是真实的。
我们可以很容易地在真和假之间使用!运算符进行切换,它也会将类型转换为Boolean。比如:
const isTrue = !0;
const isFasle = !1;
const isFasle = !!0 // !0 => true,true的反即是false
console.log(isTrue)
> Result: true
console.log(typeof isTrue)
> Result: 'boolean'
这种类型的转换在条件语句中非常方便,比如将!1当作false。
转换为字符串
我们可以使用运算符+后紧跟一组空的引号’'快速地将数字或布尔值转为字符串:
const val = 1 + ''
const val2 = false + ''
console.log(val)
> Result: "1"
console.log(typeof val)
> Result: "string"
console.log(val2)
> Result: "false"
console.log(typeof val2)
> Result: "string"
转换为数值
上面我们看到了,使用+紧跟一个空的字符串’'就可以将数值转换为字符串。相反的,使用加法运算符+可以快速实现相反的效果。
let int = '12'
int = +int
console.log(int)
> Result: 12
console.log(typeof int)
> Result: 'number'
用同样的方法可以将布尔值转换为数值:
console.log(+true)
> Return: 1
console.log(+false)
> Return: 0
在某些上下文中,+会被解释为连接操作符,而不是加法运算符。当这种情况发生时,希望返回一个整数,而不是浮点数,那么可以使用两个波浪号~~。双波浪号~~被称为按位不运算符,它和-n - 1等价。例如, ~15 = -16。这是因为- (-n - 1) - 1 = n + 1 - 1 = n。换句话说,~ - 16 = 15。
我们也可以使用~~将数字字符串转换成整数型:
const int = ~~'15'
console.log(int)
> Result: 15
console.log(typeof int)
> Result: 'number'
同样的,NOT操作符也可以用于布尔值: ~true = -2,~false = -1。
浮点数转换为整数
平常都会使用Math.floor()、Math.ceil()或Math.round()将浮点数转换为整数。在JavaScript中还有一种更快的方法,即使用|(位或运算符)将浮点数截断为整数。
console.log(23.9 | 0);
> Result: 23
console.log(-23.9 | 0);
> Result: -23
|的行为取决于处理的是正数还是负数,所以最好只在确定的情况下使用这个快捷方式。
如果n是正数,则n | 0有效地向下舍入。如果n是负数,它有效地四舍五入。更准确的说,该操作删除小数点后的内容,将浮点数截断为整数。还可以使用~~来获得相同的舍入效果,如上所述,实际上任何位操作符都会强制浮点数为整数。这些特殊操作之所以有效,是因为一旦强制为整数,值就保持不变。
|还可以用于从整数的末尾删除任意数量的数字。这意味着我们不需要像下面这样来转换类型:
let str = "1553";
Number(str.substring(0, str.length - 1));
> Result: 155
我们可以像下面这样使用|运算符来替代:
console.log(1553 / 10 | 0)
> Result: 155
console.log(1553 / 100 | 0)
> Result: 15
console.log(1553 / 1000 | 0)
> Result: 1
使用!!操作符转换布尔值
有时候我们需要对一个变量查检其是否存在或者检查值是否有一个有效值,如果存在就返回true值。为了做这样的验证,我们可以使用!!操作符来实现是非常的方便与简单。对于变量可以使用!!variable做检测,只要变量的值为:0、null、" "、undefined或者NaN都将返回的是false,反之返回的是true。比如下面的示例:
function Account(cash) {
this.cash = cash;
this.hasMoney = !!cash;
}
var account = new Account(100.50);
console.log(account.cash);
> Result: 100.50
console.log(account.hasMoney);
> Result: true
var emptyAccount = new Account(0);
console.log(emptyAccount.cash);
> Result: 0
console.log(emptyAccount.hasMoney);
> Result: false
在这个示例中,只要account.cash的值大于0,那么account.hasMoney返回的值就是true。
还可以使用!!操作符将truthy或falsy值转换为布尔值:
!!"" // > false
!!0 // > false
!!null // > false
!!undefined // > false
!!NaN // > false
!!"hello" // > true
!!1 // > true
!!{} // > true
!![] // > true