12 个 JavaScript代码片段,解决日常开发问题
web前端开发
共 3077字,需浏览 7分钟
·
2021-10-30 10:07
英文 | https://medium.com/geekculture/12-javascript-pro-snippet-codes-for-everyday-problems-678d510b28de
翻译 | 杨小爱
// Data Filteration
var data = ["Football", "Soccer", "Cricket", "Basketball", "Hockey"]
var filtered_data = data.filter(data => data.length < 8)
console.log(filtered_data)
// ["Soccer", "Cricket", "Hockey"]
// looping throught objectslet
data = {JavaScript: 1, Dart: 2, Java: 3};Object.keys(data).forEach((key, value) => { console.log(key, value); });
// Output
// JavaScript 0
// Dart 1
// Java 2
// Destructive Assignment
let data = ["Haider", "22", "50000", "Web Developer"]
let [name, age, salary, profession] = data
console.log(name, age, salary, profession)
// Haider 22 50000 Web Developer
// Slicing An Array
let array = [10, 12, 13, 14, 15, 16]
console.log(array.slice(0, 3))
// [10, 12, 13]
console.log(array.slice(0, 2))
// [10, 12]
// Search Object in Array
let data = [
{name:"haider", Salary:60000},
{name:"John", Salary:50000},
{name:"Peter", Salary:20000},
]
let emp = data.find(data => data.name === "Peter")
console.log(emp)
// Output
{
name:"Peter",
Salary:20000
}
// String Reverse
var reverse = (data) => {return data.split("").reverse().join(""); }
console.log(reverse("CoderBoy")) // yoBredoC
console.log(reverse("Medium")) // muideM
let arr1 = [10, 20, 30]
let arr2 = [40, 50]
var arr = arr1.concat(arr2)console.log(arr)
// [10, 20, 30, 40, 50]
// Capture Right Click
window.oncontextmenu = () => {console.log("Right Click is Pressed!")}
// Built in Sorting
var num = [9, 8, 4, 2, 8, 0, 3, 8]
num.sort()
console.log(num) //[0, 2, 3, 4, 8, 8, 9]
// Error Handling
try {
// Code Block to try
}
catch(err) {
// Code Block to handle errors
}
finally {
// Code Block to be executed regardless of the try and catch results
}
// Index of Element
var num = [9, 8, 4, 2, 8, 0, 3, 8]
console.log(num.indexOf(9))
// 0
console.log(num.indexOf(3))
// 6
console.log(num.indexOf(8))
// 1
// Check for UpperCase
const CheckUpper = string => string === string.toUpperCase();
console.log(CheckUpper("Hello"))
// false
console.log(CheckUpper("LEARN"))
// true
学习更多技能
请点击下方公众号
评论