简体   繁体   English

我想在不使用 forEach 或过滤器或 map 的情况下打印所有元素的索引

[英]I want to print index of all elements without using forEach or filter or map

Here is my code it is giving me the same index number of the element.这是我的代码,它为我提供了相同的元素索引号。

I want it like this 0,1,2,3,4,5,6我想要这样0,1,2,3,4,5,6

let as=[1, 2, 3, 4, 5, 5,5]

for(let i=0;i<as.length;i++){
  console.log(as[i], as.indexOf(as[i]))
}

Here is my output :这是我的 output

1 0
2 1
3 2
4 3
5 4
5 4
5 4

If I understand your question correctly, you want to fetch the index of the elements available in an array.如果我正确理解你的问题,你想获取数组中可用元素的索引。 If Yes, Then you can do like this :如果是,那么你可以这样做

 let as = [1, 2, 3, 4, 5, 5,5]; const indexArray = as.map((item, index) => index); console.log(indexArray.join(','));

Create an array you can push the indexes into, and then create a string with join .创建一个可以将索引推入的数组,然后使用join创建一个字符串。

 const as = [1, 2, 3, 4, 5, 5, 5]; let out = []; for (let i = 0; i < as.length; i++) { out.push(i); } console.log(out.join(','));

Try this:尝试这个:

let as=[1, 2, 3, 4, 5, 5,5]

for(let i=0;i<as.length;i++){
  console.log(as[i], as.indexOf(as[i],i))
}

Explaination: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf解释: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 希望通过使用Javascript map,reduce,foreach,filter方法来实现功能 - Want to achieve functionality by using Javascripts map,reduce,foreach,filter methods 如何使用map和foreach过滤数组中不在另一个数组中的元素 - How to filter elements in an array that are not in another array using map and foreach 我有一个数据,想将所有元素映射到其他元素 - I have a data and want to map all the elements to other elements 我想使用 Javascript 填充所有这些元素 - I want to fill all these elements using Javascript 使用forEach,map或filter克隆和操作嵌套对象,而无需修改原始对象 - Cloning and manipulating nested object using forEach, map, or filter without modifying original object 我想打印数组的最后一个 &#39;n&#39; 元素 - I want to print the last 'n' elements of an array 如果我想使用 forEach 循环显示数组中的前 5 个元素怎么办? - What to do if i want to show the first 5 elements from the array by using forEach loop? Knockoutjs:如何在不使用if的情况下过滤foreach绑定 - Knockoutjs: how to filter a foreach binding without using if map,filter和for和forEach之间的区别以及与for和forEach循环相比,使用map和filter的优点是什么? - Difference between map, filter vs for and forEach and what would be the advantages of using map and filter over For and forEach loops? 如何在不使用 forEach() 的情况下循环 HTML 元素? - HOW TO LOOP HTML ELEMENTS WITHOUT USING forEach()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM