最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create a New Index Array - Stack Overflow

programmeradmin0浏览0评论

Not sure why this isn't working.

Instructions:

// Create a function called indexFinder that will loop over an array and return a new array of the indexes of the contents e.g. [243, 123, 4, 12] would return [0,1,2,3]. Create a new variable called 'indexes' and set it to contain the indexes of randomNumbers.

Tried Solution:

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];

function indexFinder(arr){
  for(var i = 0; arr.length; i++){
    indexes.push(i);
  }

  return indexes;
}

indexFinder(randomNumbers);
console.log(indexes);

Not sure why this isn't working.

Instructions:

// Create a function called indexFinder that will loop over an array and return a new array of the indexes of the contents e.g. [243, 123, 4, 12] would return [0,1,2,3]. Create a new variable called 'indexes' and set it to contain the indexes of randomNumbers.

Tried Solution:

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];

function indexFinder(arr){
  for(var i = 0; arr.length; i++){
    indexes.push(i);
  }

  return indexes;
}

indexFinder(randomNumbers);
console.log(indexes);
Share Improve this question asked May 4, 2018 at 23:51 PBandJ333PBandJ333 2025 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

You have no real condition test in your for loop because arr.length, when above 0, is always truthy.

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];

function indexFinder(arr){
  for(var i = 0; i < arr.length; i++){
    indexes.push(i);
  }

  return indexes;
}

indexFinder(randomNumbers);
console.log(indexes);

But there's a much more concise way of doing this:

const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
const indexFinder = arr => arr.map((_, i) => i);
console.log(indexFinder(randomNumbers));

Another method is using Array.from

const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
console.log(Array.from(randomNumbers, x => randomNumbers.indexOf(x)));

Or we can use keys

const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
console.log([...Array(randomNumbers.length).keys()])

The problem is the condition within that for-loop using just arr.length because for length greater than 0 will be always true.

An alternative is using the function Array.from:

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0],
    indexes = Array.from({length: randomNumbers.length}, (_, i) => i);
    
console.log(indexes);

Another alternative is getting the length and then execute a simple for-loop.

发布评论

评论列表(0)

  1. 暂无评论