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

javascript - Wrap items in an array with a character - Stack Overflow

programmeradmin5浏览0评论

I have an array [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20].

Whenever the element of the array is equal to 20 I would like to wrap it with an asterisk on either side like this [1, 5, *20*, 17, 6, 12, 13, *20*, 1 , 14, *20*].

How can I achieve this?

I have an array [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20].

Whenever the element of the array is equal to 20 I would like to wrap it with an asterisk on either side like this [1, 5, *20*, 17, 6, 12, 13, *20*, 1 , 14, *20*].

How can I achieve this?

Share Improve this question edited Feb 17, 2021 at 15:13 mkrieger1 23.5k7 gold badges64 silver badges82 bronze badges asked Jun 6, 2018 at 13:55 firewire167firewire167 1391 gold badge3 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You can use map

let arr = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20]

let result = arr.map(o => o === 20 ? '*20*' : o);

console.log(result);

Doc: map()

You can use Arrays forEach to modify the elements of the array. elem is each element and i is the respective index. We are using forEach to modify the existing array. Since this is what you desired..

let arr = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20]

arr.forEach((elem, i) => {
  if (elem === 20) {
    arr[i] = "*20*"
  }
})

console.log(arr)



function rollDice(max, times, bonus) {
        var rolls = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20];
        rolls.forEach((elem, i) => { if (elem === 20) { rolls[i] = "twenty" } });
        for (var i = 0; times > i; i++)
        { 
            max = Math.floor(max);
            rolls.push(Math.floor(Math.random() * max) + 1 | + parseInt(bonus));
        }
        console.log(rolls);
} 
    
rollDice(20, 5);

The problem you are experiencing is that you need to convert the integer number into strings. JavaScript has several ways to cleverly do this behind-the-scenes, but if you are still gaining an understanding of that, it's better to be explicit about what data types you start with (integers), and what data types you expect to end with (strings).

You transform the array, "mapping" over each item, transforming it to a string, and then if the string matches "20", you add the asterisks.

const start_array = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20];

const new_array = start_array.map((integer) => {
  let number_string = integer.toString();
  if (number_string === "20") {
    number_string = "*" + number_string + "*";
  }
  return number_string;
})

console.log(new_array);
发布评论

评论列表(0)

  1. 暂无评论