简体   繁体   English

如何用 Javascript 中的相同元素替换数组中的某些元素?

[英]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] .无论如何,让我们以这个数组为例, [A, A, A, A, A] If I put in 1 rating, then the array will change to show [B, A, A, A, A] .如果我输入1评分,则数组将更改为显示[B, A, A, A, A] If 2 ratings, then the array will be [B, B, A, A, A] , and so on...如果有2评分,则数组将为[B, B, A, A, A] ,依此类推...

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.您可以通过查看索引 map。

 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.可以使用fill function,传递3个参数,如下。

the first you pass the letter you want to use to replace, in your example, the letter "A"第一个你传递你想用来替换的字母,在你的例子中,字母"A"

in the second you put the starting position, in this case the 0在第二个中,您放置起始 position,在这种情况下为 0

and in the third, the number of times the letter A will repeat, according to its rating第三个是字母A重复的次数,根据它的等级

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;
}

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

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