freecodecamp 基础数据结构-检查对象是否具有某个属性
请完善这个函数,如果传递给它的对象包含四个名字 Alan、Jeff、Sarah 和 Ryan,函数返回 true,否则返回 false。
let users = {
Alan: {
age: 27,
online: true,
},
Jeff: {
age: 32,
online: true,
},
Sarah: {
age: 48,
online: true,
},
Ryan: {
age: 19,
online: true,
},
};
function isEveryoneHere(userObj) {
}
console.log(isEveryoneHere(users)); // true
freecodecamp 基础数据结构-找出字符串中的最长单词
function findLongestWordLength(str) {
return str.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
freecodecamp 基础数据结构-按参数过滤数组
//`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` 应返回 `8`。
function findElement(arr, func) {
let num = 0;
return num;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
freecodecamp 基础算法-找出多个数组中的最大数字
// 方法一 map
function largestOfFour(arr) {
return arr.map(item => Math.max(...item))
}
largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1],
]); // [5, 27, 39, 1001]
// 方法二 for循环
function largestOfFour(arr) {
let res = [];
for(let i = 0; i < arr.length; i++) {
let max = - Infinity;
for(let j = 0; j < arr[i].length; j ++) {
max = Math.max(max, arr[i][j]);
}
res.push(max)
}
return res;
}
将字符串中的大写转小写 小写转大写
str.replace(regexp|substr, newSubStr|function)
let str = 'woSHIniDie345';
str = str.replace(/[a-zA-Z]/g, content => {
// content: 每一次正则匹配的结果
// 验证是否为大写字母:把字母转换为大写后看和之前是否一样;使用ASCII码判断大写(65-90)
return content.toUpperCase() === content ? content.toLowerCase() : content.toUpperCase()
})
console.log(str);
一维数组去重
// 方法一: Set
const _deleteRepeat = (array) => {
return Array.from(new Set(array))
};
// 方法二:indexOf
const _deleteRepeat = (array) => {
let newArr = []
array.forEach(item => {
if(newArr.indexOf(item) == -1) {
newArr.push(item)
}
})
return newArr
};
// 方法三:filter再indexOf
const _deleteRepeat = (array) => {
return array.filter((item,index) => array.indexOf(item) === index);
};
字符串大小写取反(大写变小写 小写变大写)
let str = 'woshiniDiEEE';
str = str.replace(/[a-zA-Z]/g, content => {
// content为每一次正则匹配的结果
// 验证是否为大写字母 content.toUpperCase 或者content.charCodeAt在65-90之间
return content.toUpperCase() === content ? content.toLowerCase() : content.toUpperCase()
})
console.log(str); // WOSHINIdIeee
字符串匹配 存在返回其所在位置,不存在则返回-1
计算数组对象中某个属性的和
let grade = [
{ name: 'vv1', score: 90 },
{ name: 'vv2', score: 99 }
]
function sumScore(grade) {
return grade.reduce((a, c) => a + c.score,0)
}
console.log(sumScore(grade)); // 189