<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
任务
将 border-left-width 转换成 borderLeftWidth
重要程度: 5
编写函数 camelize(str) 将诸如 “my-short-string” 之类的由短划线分隔的单词变成骆驼式的 “myShortString”。
即:删除所有短横线,并将短横线后的每一个单词的首字母变为大写。
示例:
camelize("background-color") == 'backgroundColor';
camelize("list-style-image") == 'listStyleImage';
camelize("-webkit-transition") == 'WebkitTransition';
提示:使用 split 将字符串拆分成数组,对其进行转换之后再 join 回来。
<button>解决方案</button>
function camelize(str) {
return str
.split('-')
.map(
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
)
.join('');
}
过滤范围
重要程度: 4
写一个函数 filterRange(arr, a, b),该函数获取一个数组 arr,在其中查找数值大小在 a 和 b 之间的元素,并 返回它们的数组。
该函数不应该修改原数组。它应该返回新的数组。
例如:
let arr = [5, 3, 8, 1];
let filtered = filterRange(arr, 1, 4);
alert( filtered );
alert( arr );
解决方案
function filterRange(arr, a, b){
return arr.filter(item => (item > a && item < b))
}
let arr = [5, 3, 8, 1];
let filtered = filterRange(arr, 1, 4);
console.log(filtered);
原位(in place)过滤范围
重要程度: 4
写一个函数 filterRangeInPlace(arr, a, b),该函数获取一个数组 arr,并删除其中介于 a 和 b 区间以外的所有值。检查:a ≤ arr[i] ≤ b。
该函数应该只修改数组。它不应该返回任何东西。
例如:
let arr = [5, 3, 8, 1];
filterRangeInPlace(arr, 1, 4);
alert( arr );
解决方案
function filterRangeInPlace(arr, a, b){
arr.forEach((element, index) => {
if (element <= a || element >= b) {
arr.splice(index,1)
}
});
}
降序排列
重要程度: 4
let arr = [5, 2, 1, -10, 8];
alert( arr );
解决方案
arr.sort((a, b)=>{return b - a})
alert( arr )
复制和排序数组
重要程度: 5
我们有一个字符串数组 arr。我们希望有一个排序过的副本,但保持 arr 不变。
创建一个函数 copySorted(arr) 返回这样一个副本。
let arr = ["HTML", "JavaScript", "CSS"];
let sorted = copySorted(arr);
alert( sorted );
alert( arr );
解决方案
1
function copySorted(arr){
let temArr = []
arr.forEach(element => {
temArr.unshift(element)
});
return temArr
}
2
function copySorted(arr){
return arr.slice().sort()
}
创建一个可扩展的 calculator
重要程度: 5
创建一个构造函数 Calculator,以创建“可扩展”的 calculator 对象。
该任务由两部分组成。
首先,实现 calculate(str) 方法,该方法接受像 "1 + 2" 这样格式为“数字 运算符 数字”(以空格分隔)的字符串,并返回结果。该方法需要能够理解加号 + 和减号 -。
用法示例:
let calc = new Calculator;
alert( calc.calculate("3 + 7") );
然后添加方法 addMethod(name, func),该方法教 calculator 进行新操作。它需要运算符 name 和实现它的双参数函数 func(a,b)。
例如,我们添加乘法 *,除法 / 和求幂 **:
let powerCalc = new Calculator;
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);
let result = powerCalc.calculate("2 ** 3");
alert( result );
此任务中没有括号或复杂的表达式。
数字和运算符之间只有一个空格。
你可以自行选择是否添加错误处理功能。
解决方案
function Calculator(){
this.methods = {
"+": (a, b) => a + b,
"-": (a, b) => a - b
}
this.calculate = function(str){
let split = str.split(' '),
a = +split[0],
op = split[1],
b = +split[2]
if (!this.methods[op] || isNaN(a) || isNaN(b)) {
return NaN;
}
return this.methods[op](a, b);
}
this.addMethod = function(name, func){
this.methods[name] = func
}
}
映射到 names
重要程度: 5
你有一个 user 对象数组,每个对象都有 user.name。编写将其转换为 names 数组的代码。
例如:
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };
let users = [ john, pete, mary ];
let names =
alert( names );
解决方案
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };
let users = [ john, pete, mary ];
let names = users.map(item => item.name);
alert( names );
映射到对象
重要程度: 5
你有一个 user 对象数组,每个对象都有 name,surname 和 id。
编写代码以该数组为基础,创建另一个具有 id 和 fullName 的对象数组,其中 fullName 由 name 和 surname 生成。
例如:
let john = { name: "John", surname: "Smith", id: 1 };
let pete = { name: "Pete", surname: "Hunt", id: 2 };
let mary = { name: "Mary", surname: "Key", id: 3 };
let users = [ john, pete, mary ];
let usersMapped =
alert( usersMapped[0].id )
alert( usersMapped[0].fullName )
所以,实际上你需要将一个对象数组映射到另一个对象数组。在这儿尝试使用箭头函数 => 来编写。
解决方案
let john = { name: "John", surname: "Smith", id: 1 };
let pete = { name: "Pete", surname: "Hunt", id: 2 };
let mary = { name: "Mary", surname: "Key", id: 3 };
let users = [ john, pete, mary ];
let usersMapped = users.map(user => ({
fullName: `${user.name} ${user.surname}`,
id: user.id
}))
alert( usersMapped[0].id );
alert( usersMapped[0].fullName );
按年龄对用户排序
重要程度: 5
编写函数 sortByAge(users) 获得对象数组的 age 属性,并根据 age 对这些对象数组进行排序。
例如:
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };
let arr = [ pete, john, mary ];
sortByAge(arr);
alert(arr[0].name);
alert(arr[1].name);
alert(arr[2].name);
解决方案
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };
let arr = [ pete, john, mary ];
function sortByAge(arr) {
arr.sort((a, b) => a.age - b.age);
}
sortByAge(arr);
alert(arr[0].name);
alert(arr[1].name);
alert(arr[2].name);
随机排列数组
重要程度: 3
编写函数 shuffle(array) 来随机排列数组的元素。
多次运行 shuffle 可能导致元素顺序的不同。例如:
let arr = [1, 2, 3];
shuffle(arr);
shuffle(arr);
shuffle(arr);
所有元素顺序应该具有相等的概率。例如,可以将 [1,2,3] 重新排序为 [1,2,3] 或 [1,3,2] 或 [3,1,2] 等,每种情况的概率相等。
解决方案
function shuffle(array){
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]]
}
console.log(array);
}
let arr = [1, 2, 3];
shuffle(arr);
shuffle(arr);
shuffle(arr);
获取平均年龄
重要程度: 4
编写 getAverageAge(users) 函数,该函数获取一个具有 age 属性的对象数组,并返回平均年龄。
平均值的计算公式是 (age1 + age2 + ... + ageN) / N。
例如:
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 29 };
let arr = [ john, pete, mary ];
alert( getAverageAge(arr) );
解决方案
function getAverageAge(array){
let tem = 0
array.forEach(element => {
tem += element.age
});
return tem / array.length
}
function getAverageAge(users) {
return users.reduce((prev, user) => prev + user.age, 0) / users.length;
}
数组去重
重要程度: 4
arr 是一个数组。
创建一个函数 unique(arr),返回去除重复元素后的数组 arr。
例如:
function unique(arr) {
}
let strings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
];
alert( unique(strings) );
解决方案
function unique(arr) {
let temArr = []
arr.forEach(element => {
if (!temArr.includes(element)) {
temArr.push(element)
console.log(temArr);
}
});
return temArr
}
let strings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
];
alert( unique(strings) );
从数组创建键(值)对象
重要程度: 4
假设我们收到了一个用户数组,形式为:{id:..., name:..., age... }。
创建一个函数 groupById(arr) 从该数组创建对象,以 id 为键(key),数组项为值。
例如:
let users = [
{id: 'john', name: "John Smith", age: 20},
{id: 'ann', name: "Ann Smith", age: 24},
{id: 'pete', name: "Pete Peterson", age: 31},
];
let usersById = groupById(users);
处理服务端数据时,这个函数很有用。
在这个任务里我们假设 id 是唯一的。没有两个具有相同 id 的数组项。
请在解决方案中使用数组的 .reduce 方法。
解决方案
function groupById(arr) {
return arr.reduce((obj, value)=>{
obj[value.id] = value
return obj
}, {})
}
let users = [
{id: 'john', name: "John Smith", age: 20},
{id: 'ann', name: "Ann Smith", age: 24},
{id: 'pete', name: "Pete Peterson", age: 31},
];
let usersById = groupById(users);
console.log(usersById);
</script>
</html>
现代 JavaScript