最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How can I change elements inside and array - Stack Overflow

matteradmin7PV0评论

How can I get the "e" elements inside of "arr" to be replaced by change0?

The arr array will be an input by the user and I need to change it there is no way to predict which element will be "e".

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];

var change0 = 2

var change1 = 1

document.write(arr);

How can I get the "e" elements inside of "arr" to be replaced by change0?

The arr array will be an input by the user and I need to change it there is no way to predict which element will be "e".

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];

var change0 = 2

var change1 = 1

document.write(arr);
Share Improve this question edited Apr 16, 2017 at 11:06 ibrahim mahrir 31.7k5 gold badges49 silver badges78 bronze badges asked Apr 16, 2017 at 10:58 Peter TothPeter Toth 8001 gold badge9 silver badges36 bronze badges
Add a ment  | 

8 Answers 8

Reset to default 2

You could use map() method and this will return new updated array and save original.

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];
var change0 = 2;

var result = arr.map(e => e == 'e' ? change0 : e);
console.log(result)

You can do this using join and split methods.

var replace="change0";
var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];
console.log(arr.join().split('e').join(replace).split(','));

Run a loop for getting index of element "e" and then repeat until there are more elements left:

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];

while (arr.indexOf("e") > 0){
    var index = arr.indexOf("e");
    arr[index] = "change0";
}
document.write(arr);

You could use Array#indexOf and search for all elements and change then with the given value.

var array = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"],
    search = "e",
    change = 2,
    p = array.indexOf(search);
    
while (p !== -1) {
    array[p] = change;
    p = array.indexOf(search, p + 1);
}

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can use indexOf to determine the index of the element in an array. So basically, you can just go like this:

arr[arr.indexOf('e')] = change0;

It will not work if you have multiple element that have the values of 'e'. It will only change the first one so you have to put it through a loop. Or use map.

Using forEach:

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];

var change = "changed";

arr.forEach(function(v, i) {
  if(v === "e")
    arr[i] = change;
});

console.log(arr);

  1. Convert to string
  2. Replace 'e'
  3. Convert back to array

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];

console.log((((arr.toString()).replace(/e/g,"changed"))).split(','));

If you intend to handle more than one letter, it’s best to prepare encoder/decoder (a function or an array) in advance. Then your job bees as simple as:

output = input.map(val => encoder[val] || val);

The || val part is for values not handled by the encoder.

Working example

In this example, we use split("") to convert string to array and join("") to do the opposite.

PrepareCodec:
    var Latin    = "abcdefghijklmnoprstuvyzABCDEFGHIJKLMNOPRSTUVYZ";
    var Cyrillic = "абцдефгхийклмнопрстувызАБЦДЕФГХИЙКЛМНОПРСТУВЫЗ";
    var encoder = {}, decoder = {};
    for (let i in Latin)    encoder[Latin[i]] = Cyrillic[i];
    for (let i in Cyrillic) decoder[Cyrillic[i]] = Latin[i];

EncryptionTest:
    var src = prompt("Enter text to encrypt:", "Hello, world!");
    var enc = src.split("").map(val => encoder[val] || val).join("");
DecryptionTest:
    enc = prompt("Enter text to decrypt:", enc);
    var dec = enc.split("").map(val => decoder[val] || val).join("");
FinalResult:
    prompt("Decrypted text:", dec);

Post a comment

comment list (0)

  1. No comments so far