這篇文章給大家分享的是有關JavaScript中如何使用or循環語句的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
這大概是應用最廣的循環語句了吧,簡單實用,且大多數時候性能還是在線的,唯一的缺點大概就是太普通,沒有特色,導致很多人現在不愿用它。
const array = [4, 7, 9, 2, 6];
for (let index = 0; index < array.length; index++) {
const element = array[index];
console.log(element);
}
// 4, 7, 9, 2, 6for...in 語句可以以任意順序遍歷一個對象的除 Symbol 以外的可枚舉屬性。
const temp = {name: "temp"};
function Apple() {
this.color = 'red';
}
Apple.prototype = temp;
const obj = new Apple();
for (const prop in obj) {
console.log(`obj.${ prop } = ${ obj[prop] }`);
}
// obj.color = red
// obj.name = temp如果你只要考慮對象本身的屬性,而不是它的原型,那么使用 getOwnPropertyNames() 或執行 hasOwnProperty() 來確定某屬性是否是對象本身的屬性。
const temp = {name: "temp"};
function Apple() {
this.color = 'red';
}
Apple.prototype = temp;
const obj = new Apple();
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(`obj.${ prop } = ${ obj[prop] }`);
}
}
// obj.color = red當然,也可以用來遍歷數組。
const arr = [1, 2, 3, 4, 5];
for (const key in arr) {
console.log(key)
}
// 0,1,2,3,4使用 for...in 可以遍歷數組,但是會存在以下問題:
index 索引為字符串型數字(注意,非數字),不能直接進行幾何運算。
遍歷順序有可能不是按照實際數組的內部順序(可能按照隨機順序)。
所以一般不建議使用 for...in 來遍歷數組。
for...of 語句在可迭代對象(包括 Array,Map,Set,String,TypedArray,arguments 對象等等)上創建一個迭代循環,調用自定義迭代鉤子,并為每個不同屬性的值執行語句。
const array = ['a', 'b', 'c'];
for (const element of array) {
console.log(element);
}
// a
// b
// cfor...of 和 for...in 的區別:
for...in 語句以任意順序迭代對象的可枚舉屬性。
for...of 語句遍歷可迭代對象定義要迭代的數據。
Object.prototype.objCustom = function () { };
Array.prototype.arrCustom = function () { };
let iterable = [3, 5, 7];
iterable.foo = 'hello';
for (const key in iterable) {
console.log(key); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
// 0, 1, 2, "foo", "arrCustom", "objCustom"
for (const key of iterable) {
console.log(key);
}
// 3, 5, 7使用 for...of 遍歷 Map 結構:
let nodes = new Map();
nodes.set("node1", "t1")
.set("node2", "t2")
.set("node3", "t3");
for (const [node, content] of nodes) {
console.log(node, content);
}
// node1 t1
// node2 t2
// node3 t3可以看出,使用 for...of 遍歷 Map 結構還是挺方便的,推薦使用!
如果普通 for 循環用膩了,推薦使用 for...of 來替代。
這三種循環都可以使用 break 關鍵字來終止循環,也可以使用 continue 關鍵字來跳過本次循環。
for...of 循環的適用范圍最大。
感謝各位的閱讀!關于“JavaScript中如何使用or循環語句”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。