for (var index in myArray) { // 不推荐这样 console.log(myArray[index]); } 不推荐用for-in来循环一个数组,因为,不像对象,数组的index跟普通的对象属性不一样,是重要的数值序列指标。 总之,for–in是用来循环带有字符串key的对象的方法。 for-of循环 Java6里引入了一种新的循环方法,它就是for-of循...
如需访问每个值的索引,可以使用for...in循环。 let arr = [10, 20, 30, 40]; //Longhand for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } //Shorthand //for of loop for (const val of arr) { console.log(val); } //for in loop for (const index in arr) ...
for(letindexofarr.keys()){console.log(`索引:${index}`);}for(let[index,item]ofarr.entries()){console.log(`索引:${index},元素:${item}`);} 复制代码遍历字符串。 varstr="hello";for(letitemofstr){console.log(item);// h e l l o} 复制代码遍历Map对象 varmyMap=newMap();myMap.se...
for(letkeyofarr.keys()){// key是下标console.log(key)}for(letvalueofarr){// value是值console.log(value)}for(letvalueofarr.values()){// value是值console.log(value)}for(let[key,value]ofarr.entries()){// key是下标 value是值console.log(key,value)} Object 代码语言:javascript 复制 for(...
五、For...of 可直接遍历数组的元素的值,对于遍历数组来说非常方便,推荐使用这种方法,如下: 六、Foreach 它可以遍历数组中的每一项,没有返回值,对原数组无影响,而且不止IE浏览器。如下: 七、Filter 根据指定条件来遍历数组但不改变原始数组,返回新数组,相当于一个过滤器,如下: ...
const array1 = [5, 12, 8, 130, 44]; const isLargeNumber = (element) => element > 13; console.log(array1.findIndex(isLargeNumber)); // expected output: 3 参考文献 The Complete Guide to Loops in JavaScript Loops and iteration(花几分钟时间重温) ...
indexOf + lastIndexOf这种方法的思路是如果一个元素查找她的索引,从前获得和从后获得的索引一样,则必然是唯一的,如果不一样说明有重复,删除最后一个并将计数 i-1。function fn6(){ for(let i =0;i<arr.length;i++){ if(arr.indexOf(i)!=arr.lastIndexOf(i)){ arr.splice(arr.lastIndexOf(i),...
平时工作中循环的使用场景可以说是非常之多了,昨天改别人代码时候有位同事非常喜欢用ES6等新特性,一个数组的遍历全部都是用for...of...,然后业务需求要用...
三、利用indexOf去重 function unique(arr) {if(!Array.isArray(arr)) { console.log('type error!')return}vararray =[];for(vari =0; i < arr.length; i++) {if(array .indexOf(arr[i]) === -1) { array .push(arr[i]) } }returnarray; }vararr = [1,1,'true','true',true,true...
for (let x of language) { text += x + " "; } Try it Yourself » Learn more in the chapter: JavaScript Loop For/In/Of.JavaScript MapsBeing able to use an Object as a key is an important Map feature.Example const fruits = new Map([ ["apples", 500], ["bananas", 300], [...