简体   繁体   中英

How to replace certain number of elements in array with a same element in Javascript?

I'm making a star rating component. I already filled the array with empty stars. I wanted to input a number so that when a number is entered, a certain number of stars are replaced with filled stars.

Anyway, let's take this array as an example, [A, A, A, A, A] . If I put in 1 rating, then the array will change to show [B, A, A, A, A] . If 2 ratings, then the array will be [B, B, A, A, A] , and so on...

I know about splice and loops but I couldn't figure out how to make it work with just the entered number and then replace it with another element. I tried to look online but no success.

You could map by looking at the index.

 var array = ['A', 'A', 'A', 'A', 'A'], stars = 2; console.log(...array); array = array.map((v, i) => i < stars? 'B': v); console.log(...array);

You can use the fill function, passing 3 parameters, as follows.

the first you pass the letter you want to use to replace, in your example, the letter "A"

in the second you put the starting position, in this case the 0

and in the third, the number of times the letter A will repeat, according to its rating

Ex:

 let arr = ['A', 'A', 'A', 'A', 'A'] // ['B', 'A', 'A', 'A', 'A'] console.log( arr.fill('B', 0, 1) ) // ['B', 'B', 'A', 'A', 'A'] console.log( arr.fill('B', 0, 2) ) // ['B', 'B', 'B', 'A', 'A'] console.log( arr.fill('B', 0, 3) )

let arr = ['A', 'A', 'A', 'A', 'A'];
let input = 6;   //sample rating input
input = (input<=125) ? input:125; //To limit the max rating to Z
let i=0, j=0;
while(j<input){
    arr[i] = String.fromCharCode(arr[i].charCodeAt(0) + 1);  //convert char to ascii, increment by one, and convert back to char
    i++;
    j++;
    if(i===5)   i=0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM