小编给大家分享一下10个JavaScript的实用技巧,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
arguments 对象是函数内部可访问的类似数组的对象,其中包含传递给该函数的参数的值。
但这与其他数组不同,我们可以访问值并获取长度,但是不能对其使用其他数组方法。
幸运的是,我们可以把它转换成一个常规数组:
var argArray = Array.prototype.slice.call(arguments);
我最初的直觉是使用循环,但是那样做太费事了。
var numbers = [3, 5, 7, 2];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 17
我们有以下代码:
if (hungry) {
goToFridge();
}
通过将变量与函数一起使用,我们可以使其更短:
hungry && goToFridge()
||
我过去常常在函数的开头声明自己的变量,以避免在出现任何意外错误时出现 undefined
的情况。
function doSomething(arg1){
arg1 = arg1 || 32; // if it's not already set, arg1 will have 32 as a default value
}
逗号运算符( ,
)可以评估其每个操作数(从左到右)并返回最后一个操作数的值。
let x = 1;
x = (x++, x);
console.log(x);
// expected output: 2
x = (2, 3);
console.log(x);
// expected output: 3
我们可以使用length属性来调整数组大小或清空数组
var array = [11, 12, 13, 14, 15];
console.log(array.length); // 5
array.length = 3;
console.log(array.length); // 3
console.log(array); // [11,12,13]
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解压缩为不同的变量。
let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // -> 2
console.log(b) // -> 1
每天我都在随机排列
随机排列,随机排列
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(list.sort(function() {
return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]
你可以在声明对象之前分配动态属性。
const dynamic = 'color';
var item = {
brand: 'Ford',
[dynamic]: 'Blue'
}
console.log(item);
// { brand: "Ford", color: "Blue" }
对于所有ES6爱好者,我们可以通过使用带有扩展运算符(spread)的Set对象来创建一个仅包含唯一值的新数组。
const my_array = [1, 2, 2, 3, 3, 4, 5, 5]
const unique_array = [...new Set(my_array)];
console.log(unique_array); // [1, 2, 3, 4, 5]
以上是“10个JavaScript的实用技巧”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。