要代碼:
Dim doc, objhtml As Object
Dim i As Integer
Dim strhtml As String
If Not Me.WebBrowser1.Busy Then
Set doc = WebBrowser1.Document
i = 0
Set objhtml = doc.body.createtextrange()
If Not IsNull(objhtml) Then
Text1 = objhtml.htmltext
End If
End If
?
示例下載:( 在“了解更多”里下載)
圖 示:
avaScript不斷發展壯大,
因為它是最容易上手的語言之一,因此為市場上的新成為技術怪才打開了大門。(問號臉?)
的確,JavaScript可以做很多出色的事情!還有很多東西要學習。
而且,無論你是JavaScript的新手還是更多的專業開發人員,學習新知識總是一件好事。
本文整理了一些非常有用的單行代碼(20+),這些單行代碼可以幫助你提高工作效率并可以幫助調試代碼。
什么是單行代碼?
單行代碼是一種代碼實踐,其中我們僅用一行代碼執行某些功能。
此函數將使用Math.random()方法返回布爾值(真或假)。
Math.random創建一個介于0和1之間的隨機數,然后我們檢查它是否大于或小于0.5。
這意味著有50/50的機會會得到對或錯。
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
通過此功能,你將能夠檢查提供的日期是工作日還是周末。
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
簡單的實用程序功能,用于檢查數字是偶數還是奇數。
const isEven = (num) => num % 2 === 0;
console.log(isEven(5));
// false
console.log(isEven(4));
// true
從數組中刪除所有重復值的非常簡單的方法。此函數將數組轉換為Set,然后返回數組。
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
一種檢查變量是否為數組的干凈簡便的方法。
當然,也可以有其他方法
const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
這將以兩個數字為參數,并將在這兩個數字之間生成一個隨機數!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// could be anything from 1 - 50
也許你需要臨時的唯一ID,這是一個技巧,你可以使用它在旅途中生成隨機字符串。
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!
所述window.scrollTo()方法把一個X和Y坐標滾動到。
如果將它們設置為零和零,我們將滾動到頁面頂部。
image.png
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
切換布爾值是非常基本的編程問題之一,可以通過許多不同的方法來解決。
代替使用if語句來確定將布爾值設置為哪個值,你可以使用函數使用!翻轉當前值。非運算符。
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
//or
const toggleBool = b => !b;
下面的代碼是不使用第三個變量而僅使用一行代碼即可交換兩個變量的更簡單方法之一。
[foo, bar] = [bar, foo];
要計算兩個日期之間的天數,
我們首先找到兩個日期之間的絕對值,然后將其除以86400000(等于一天中的毫秒數),最后將結果四舍五入并返回。
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
PS:你可能需要添加檢查以查看是否存在navigator.clipboard.writeText
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text);
};
有兩種合并數組的方法。其中之一是使用concat方法。另一個使用擴展運算符(…)。
PS:我們也可以使用“設置”對象從最終數組中復制任何內容。
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
人們有時會使用庫來查找JavaScript中某些內容的實際類型,這一小技巧可以節省你的時間(和代碼大小)。
const trueTypeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
需要從頭開始截斷字符串,這不是問題!
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};
console.log(
truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...
從中間截斷字符串怎么樣?
該函數將一個字符串作為第一個參數,然后將我們需要的字符串大小作為第二個參數,然后從第3個和第4個參數開始和結束需要多少個字符
const truncateStringMiddle = (string, length, start, end) => {
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};
console.log(
truncateStringMiddle(
'A long story goes here but then eventually ends!', // string
25, // 需要的字符串大小
13, // 從原始字符串第幾位開始截取
17, // 從原始字符串第幾位停止截取
),
);
// A long story ... eventually ends!
好吧,不幸的是,JavaScript沒有內置函數來大寫字符串,但是這種解決方法可以實現。
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world
此簡單的幫助程序方法根據選項卡是否處于視圖/焦點狀態而返回true或false
const isTabInView = () => !document.hidden; // Not hidden
isTabInView();
// true/false
如果用戶使用的是Apple設備,則返回true
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false
當你只想在一行中編寫if..else語句時,這是一個很好的代碼保護程序。
// Longhand
const age = 18;
let greetings;
if (age < 18) {
greetings = 'You are not old enough';
} else {
greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
在將變量值分配給另一個變量時,可能要確保源變量不為null,未定義或為空。
可以編寫帶有多個條件的long if語句,也可以使用短路評估。
avaScript 的故事很長。在今天,JavaScript 的運行從移動設備到服務器端,無論您是計劃在 2022 年學習或使用 JavaScript ,還是目前正在使用JavaScript進行開發,還是已經熟練掌握了JavaScript技能,我在這里與您分享的這17個高頻使用的JavaScript代碼段,對您一定會有一些幫助。
好了,我們現在就開始吧。
1、短路表達式
const defaultSafeValue = "defaultSafeValue"
let someValueNotSureOfItsExistence = null
let expectingSomeValue = someValueNotSureOfItsExistence || defaultSafeValue
console.log(expectingSomeValue)
如果 someValueNotSureOfItsExistance 為 undefined/null/false,則 defaultSafeValue 將就位。
如果我們不確定任何值是否存在,這會很方便。它還確保您不會從錯誤的對象中查看任何內容,即如下所示。
let someValueNotSureOfItsExistence = null
// let someValueNotSureOfItsExistence = { expectingSomeValue:1 }
let { expectingSomeValue } = someValueNotSureOfItsExistence || {}
console.log(expectingSomeValue)
你可以在上面的代碼中取消注釋,看看它可以避免可能的崩潰。
2、IF條件
let someValue = true // or some value like 1,.. {} etc
if(someValue){
console.log('Yes. Its exist')
}
3、多重條件
const conditions = ["Condition 2","Condition String2"];someFunction(str){
if(str.includes("someValue1") || str.includes("someValue2")){
return true
}else{
return false
}
}
同樣可以通過以下方式完成
someFunction(str){
const conditions = ["someValue1","someValue2"];
return conditions.some(condition=>str.includes(condition));
}
4、模板文字
let name = "John Doe", profession = "Engineering"
let someSentence = `My Name is ${name} and he is doing ${profession}`
console.log(someSentence)
// His Name is John Doe and he is doing Engineering
5、解構賦值
let personObject = {
name:"John Doe",
phone:"1234",
address:{
line:"abc ave",
postCode:12223,
},
}
const {name, phone, address} = personObject;
我們經常在像 React 這樣的框架中這樣做,如下所示
import { observable, action, runInAction } from 'mobx';
6、擴展運算符
const previousNumber = [1, 3, 5 ];
const allNumbers = [2 ,4 , 6, ...previousNumber];
console.log(allNumbers);
// [ 2, 4, 6, 1, 3, 5 ]
//Handy if you want to merge two objects
7、箭頭功能簡寫
var sayHello = (name)=>{
return "Hello " + name
}
console.log(sayHello("John"))
反而
var sayHello = (name)=> "Hello " + name
console.log(sayHello("John"))
8、條件函數調用
function fn1(){
console.log('I am Function 1');
}
function fn2(){
console.log('I am Function 2');
}
let checkValue = 3;
if(checkValue === 3){
fn1();
}else{
fn2();
}
相反,簡而言之
(checkValue ===3 ? fn1:fn2)(); // Short Version
9、&& 運算符
var value = true; // or true or some value exist
if(value){
console.log('Value is there or true')
}
// OR via this way
value && console.log('Value is there or true')
10、 將字符串轉換為數字
const numberStr1 = "100";
const numberStr2 = "200";
var sampleValue = +numberStr1 + +numberStr2;
console.log(sampleValue);
console.log(typeof sampleValue); // Its a number!
11、避免過多的函數參數
function myFunction(employeeName,jobTitle,yrExp,majorExp){
}
// you can call it via
myFunction("John","Project Manager",12,"Project Management");
// ***** PROBLEMS ARE *****
// Violation of ‘clean code’ principle
// Parameter sequencing is important
// Unused Params warning if not used
// Testing need to consider a lot of edge cases.
相反,創建一個 params 對象,如
const mockTechPeople = {
employeeName:'John',
jobTitle:'Project Manager',
yrExp:12,
majorExp:'Project Management'
}
并在函數中解構 params 使其更清晰,產生錯誤的可能性更小。
function myFunction({employeeName,jobTitle,yrExp,majorExp}){
// ES2015/ES6 destructuring syntax is in action
// map your desired value to variable you need.
}
現在調用很簡單
myFunction(mockTechPeople); // Only One argument
12、 默認參數值
function rectangle(h,w){
if(!h){
h=0;
}else if(!w){
w=0;
}
return h*w;
}
console.log(rectangle())
反而
function rectangle(h =0,w=0){
return h*w;
}
console.log(rectangle(1,12))
var val = "1212121212"
console.log(Math.floor(val)) // Long one
console.log(~~val) // smart one
var someNumber = 123
console.log(someNumber.toString()) //return "123"
// Or in SHORT CUT
console.log(`${someNumber}`) //return "123"
for(let i=0;i<1e3;i++){ // instead of i<1000, Cool, right?
}
var x='x',y='y'
var obj = {x,y} // instead of {x:x, y:y}
console.log(obj)
*請認真填寫需求信息,我們會在24小時內與您取得聯系。