1、字符串
1.sum two numbers
function myFunction(a, b)
{
return a+b
}
2.Comparison operators, strict equality
function myFunction(a, b)
{
return a === b
}
3.Get type of value
function myFunction(a)
{
return typeof(a)
}
4.Get nth character of string
function myFunction(a, n) {
return a[n-1]
}
5.Remove first n characters of string
function myFunction(a) {
return a.slice(3)
}
6.Get last n characters of string
function myFunction(str) {
return str.slice(str.length-3)
}
7.Get first n characters of string
function myFunction(a) {
return a.slice(0, 3)
}
8.Extract first half of string
function myFunction(a) {
return a.slice(0, a.length / 2)
}
9.Remove last n characters of string
function myFunction(a) {
return a.slice(0,a.length-3)
}
10.Check if a number is even
function myFunction(a) {
return a % 2 === 0
}
2、数组
1.Get nth element of array
function myFunction(a, n) {
return a[n-1]
}
2.Remove first n elements of an array
function myFunction(a) {
return a.slice(3)
}
3.Get last n elements of an array
function myFunction(a) {
return a.slice(-3)
}
4.Get first n elements of an array
function myFunction(a) {
return a.slice(0,3)
}
5.Remove a specific array element
function myFunction(a,b) {
return a.filter(item => item !== b)
}
6.Count number of elements in JavaScript array
function myFunction(a) {
return a.length
}
7.Sort an array of strings alphabetically
function myFunction(arr) {
return arr.sort()
}
8.Sort an array of numbers in descending order
function myFunction(arr) {
return arr.sort((a, b) => b - a)
}
9.Calculate the sum of an array of numbers
function myFunction(a) {
let sum = 0
for(let i = 0;i<a.length;i++){
sum += a[i]
}
return sum
}
3、对象
1.Accessing object properties one
function myFunction(obj) {
return obj["country"];
}
2.Accessing object properties three
function myFunction(obj, key) {
return obj[key];
}
3.Check if property exists in object
function myFunction(a, b) {
return b in a;
}
4.Check if property exists in object and is truthy
5.Creating Javascript objects one
function myFunction(a) {
return { key: a };
}
6.Creating Javascript objects two
function myFunction(a, b) {
return {[a]:b}
}
7.Creating Javascript objects three
function myFunction(a, b) {
let obj = {}
for(let i = 0; i < a.length; i++){
obj[a[i]] = b[i]
}
return obj
}
8.Extract keys from Javascript object
function myFunction(a) {
return Object.keys(a)
}
9.Sum object values
function myFunction(a) {
return eval(Object.values(a).join("+"))
}
10.Remove a property from an object
function myFunction(obj) {
let {b,...item} = obj
return item
}