标签:function 顺序 prope log return 循环对象 prototype oar 索引
//for 循环
var array = [1,2,3,4,5,6,7]; for (var i = 0; i < array.length; i++) { console.log(i,array[i]); } //for in var array = [1,2,3,4,5,6,7]; for(let index in array) { console.log(index,array[index]); };
//forEach
var array = [1,2,3,4,5,6,7]; array.forEach(v=>{ console.log(v); }); //或者 var array = [1,2,3,4,5,6,7]; array.forEach(function(v){ console.log(v); });
//for in 循环对象
var A = {a:1,b:2,c:3,d:"hello world"}; for(let k in A){ console.log(k,A[k]); }
//在ES6中,增加了一个for of循环
var array = [1,2,3,4,5,6,7]; for(let v of array) { console.log(v); } let s = "helloabc"; for(let c of s) { console.log(c); }
//Map,Set,for of
var set = new Set(); set.add("a").add("b").add("d").add("c"); var map = new Map(); map.set("a",1).set("b",2).set(999,3); for (let v of set) { console.log(v); } console.log("--------------------"); for(let [k,v] of map) { console.log(k,v); }
//原生javascript遍历
let array1 = [‘a‘,‘b‘,‘c‘]; for (let i = 0;i < array1.length;i++){ console.log(array1[i]); // a b c }
//forEach() 方法对数组的每个元素执行一次提供的函数。总是返回undefined;
//map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。返回值是一个新的数组;
var array1 = [1,2,3,4,5]; var x = array1.forEach(function(value,index){ console.log(value); //可遍历到所有数组元素 return value + 10 }); console.log(x); //undefined 无论怎样,总返回undefined var y = array1.map(function(value,index){ console.log(value); //可遍历到所有数组元素 return value + 10 }); console.log(y); //[11, 12, 13, 14, 15] 返回一个新的数组
// 因为迭代的顺序是依赖于执行环境的,所以数组遍历不一定按次序访问元素。 因此当迭代那些访问次序重要的 arrays 时用整数索引去进行 for 循环
let array2 = [‘a‘,‘b‘,‘c‘] let obj1 = { name : ‘lei‘, age : ‘16‘ } for(variable in array2){ //variable 为 index console.log(variable ) //0 1 2 } for(variable in obj1){ //variable 为属性名 console.log(variable) //name age }
//for...in循环会遍历一个object所有的可枚举属性。
//for...of会遍历具有iterator接口的数据结构
//for...in 遍历(当前对象及其原型上的)每一个属性名称,而 for...of遍历(当前对象上的)每一个属性值
Object.prototype.objCustom = function () {}; Array.prototype.arrCustom = function () {}; let iterable = [3, 5, 7]; iterable.foo = "hello"; for (let i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" } for (let i of iterable) { console.log(i); // logs 3, 5, 7 }
//js 实现获取对象所有键名(key)的方法
var jsonObject1 = { "name": "xiaoming", "age": 29 }; var keys1 = []; for (var p1 in jsonObject1) { if (jsonObject1.hasOwnProperty(p1)) keys1.push(p1); } console.log(keys1); //name,age
//js 实现获取对象所有键名(key)的方法
Object.prototype.test = "I am test"; var jsonObject = { "name": "xiaoming", "age": 29 }, keys = []; for (var p in jsonObject) keys.push(p); console.log(keys); //name,age,test
//提取对象的key值
checklist=[{"sensor_board":{"cur":"1.0.0","new":"1.0.1"}},{"sensor_board":{"cur":"1.0.0","new":"1.0.1"}}] keys=[] for (var p in checklist[0]){ keys.push(p); } console.log(keys)
标签:function 顺序 prope log return 循环对象 prototype oar 索引
原文地址:https://www.cnblogs.com/sea-stream/p/10765799.html