傳統的JS循環方法,while,do while,for與其餘語言相似,本文不作過多描述,更多的集中在:數組
var obj = {"name":"sme","sex":"female"};
Object.defineProperty(obj, "age", {value:"18", enumerable:false});//增長不可枚舉的屬性age
Object.prototype.protoPer1 = function(){console.log("name is sme");};//經過原型鏈增長屬性,爲一個函數
for(var a in obj){
console.log(a);
}
// 輸出:name,sex,ProtoPer1
//注意:屬性age爲不可可枚舉,因此沒有輸出。
複製代碼
for (const value of strings) {
console.log(value);
}
複製代碼
var arr = [1,2,3];
arr.forEach(
function(value,index,arr){
console.log(index)//索引
console.log(value)//值
//如下爲錯誤代碼
//if(index/2 === 0){
// continue;
//}
},this)
複製代碼
var obj = {"name":"sme","sex":"female"};
Object.defineProperty(obj, "age", {value:"18", enumerable:false});//增長不可枚舉的屬性age
Object.prototype.protoPer1 = function(){console.log("name is sme");};//經過原型鏈增長屬性,爲一個函數
console.log(Object.getOwnPropertyNames(obj));
//輸出:[name,sex,age]
//注意:返回的也是數組,原型上添加的屬性不會被遍歷到
複製代碼
var obj = {"name":"sme","sex":"female"};
Object.defineProperty(obj, "age", {value:"18", enumerable:false});//增長不可枚舉的屬性age
Object.prototype.protoPer1 = function(){console.log("name is sme");};//經過原型鏈增長屬性,爲一個函數
console.log(Object.keys(obj));
//輸出:[name,sex]
//注意:原型上添加的屬性不會被遍歷到
複製代碼
同上例子
console.log(Object.entries(obj))
\\輸出[["name","sme"],["sex","female"]]
複製代碼
var arr = [1,2,3]
var res = arr.map(function(val,index,arr){
return val*2
})
//res=[2,4,6]
//arr=[1,2,3]
複製代碼
array.every(function(currentValue,index,arr), thisValue)
複製代碼
array.some(function(currentValue,index,arr),thisValue)
複製代碼
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
//輸出:125
複製代碼