JS 数组常用技巧

mac2024-03-25  26

删除数组的重复项 var fruits = ["banner", "apple", "orange", "watermelen", "apple", "orange", "banner"]; var uniqueFruits = Array.from(new Set(fruits)); console.log("删除数组的重复项", uniqueFruits); 替换数组中的特定值 var userNames = ['小组1', '小组2', '小组3', '小组4', '小组5']; userNames.splice(0,2, '替换0', '替换1'); console.log(userNames); Array.from 达到 .map 的效果 var friends = [ {name: '小米', age: 21}, {name: '张三', age: 22}, {name: '里斯', age: 23}, {name: '阿毛', age: 22}, {name: '小六', age: 21}, ] var friendsNames = Array.from(friends, ({name}) => name); console.log(friendsNames); ``` 4.置空数组 friends.length = 0; console.log(friends); 5. 将数组转换为对象 var friendss = ['小组', '气温低', '大众', '高尔夫']; var friendsObj01 = {...friendss}; // 将数组转换为对象 var friendsObj02 = Object.values(friendsObj01); //将对象转换为数组 console.log("01==", friendsObj01); console.log("02==", friendsObj02); // 方法2 将对象转换为数组 var friendsArr = []; for (var i in friendsObj01) { friendsArr.push(friendsObj01[i]); } console.log("方法2", friendsArr); 6. 用数据填充数组 var nweArray = new Array(10).fill('1'); console.log('用数据填充数组', nweArray); 7. 数组合并 var fruits01 = ["banner", "apple", "orange", "watermelen"]; var fruits02 = ['小组', '气温低', '大众', '高尔夫']; var fruits03 = ['小组1', '小组2', '小组3', '小组4', '小组5']; var food = [...fruits01, ...fruits02, ...fruits03]; console.log("数组合并", food); 8.求两个数组的交集 //找到两个数组的交集,首先使用上面的方法确保所检查数组中的值不重复,接着使用.filter 方法和.includes方法 var numOne = [0, 2, 4, 6, 8, 10]; var numTwo = [1, 2, 3, 4, 5, 6]; var duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item)); console.log("求两个数组的交集", duplicatedValues); 9.从数组中删除虚值 // 在 JS 中,虚值有 false, 0,'', null, NaN, undefined。咱们可以 .filter() 方法来过滤这些虚值。 var mixedArr = [0, 'blue', '', NaN, 9, null, true, undefined, 'false', 'white']; var trueArr = mixedArr.filter(Boolean); console.log(trueArr); 10. 从数组中获取随机值 var names = ['随机01', '随机02', '随机03', '随机04', '随机05', '随机06']; var randomName = names[(Math.floor(Math.random() * (names.length)))]; console.log("从数组中获取随机值", randomName); 11.反转数组 var namess = ['随机01', '随机02', '随机03', '随机04', '随机05', '随机06']; var reverseNames = namess.reverse(); console.log("反转数组", reverseNames); 12 lastIndexOf() // 返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。 var nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7]; var lastIndex = nums.lastIndexOf(5); console.log(lastIndex); 13.对数组中的所有值求和 var numss = [1, 5, 2, 6]; var sum = numss.reduce((x, y) => x+y); console.log(sum);
最新回复(0)