数组是网站建设中JS语言最常见的一种数据结构,在开发中也会经常用到,成都创新互联为大家分享一些小技巧,帮助提高网站开发效率。
1、删除数组的重复项
var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
var uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits);
var uniqueFruits2 = […new Set(fruits)];
console.log(uniqueFruits2);
2、替换数组中的特定值
有时在创建代码时需要替换数组中的特定值,有一种很好的简短方法可以做到这一点,咱们可以使用.splice(start、value to remove、valueToAdd),这些参数指定咱们希望从哪里开始修改、修改多少个值和替换新值。
var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
fruits.splice(0, 2, “potato”, “tomato”);console.log(fruits);
3、置空数组
var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
fruits.length = 0;console.log(fruits);
returns [];
4、对数组中的所有值求和
JS 面试中也经常用 reduce 方法来巧妙的解决问题
var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum);